/// <summary>获取缓存项,不存在时返回默认值</summary> /// <param name="key">键</param> /// <returns></returns> public T Get <T>(string key) { // 尝试获得值 if (_cache.TryGetValue(key, out var item) || item != null) { item.Alive = DateTime.Now.Ticks; // 设置活跃时间 if (_jsonSerialize) // 启用了Json序列化 { return(Json.Json.Deserialize <T>(item.Value.ToString())); // 尝试转换回指定类型 } else { return(TypeConvert.C2Type <T>(item.Value)); // 尝试转换回指定类型 } } return(default);
/// <summary> /// 尝试将结果转换成目标类型 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="result"></param> /// <returns></returns> private T TryConvertType <T>(object result) { // 取第一项 object value; if (result is IList <object> rs) { value = rs.FirstOrDefault(); } else { value = result; } // 转换字符串 if (value is string str) { try { switch (str) { case "OK": return((T)Commands.Ok); case "PONG": return((T)Commands.Ok); } return(TypeConvert.C2Type <T>(str)); } catch (Exception e) { throw new RedisClientException($"将字符串({value})转为类型({typeof(T).Name})失败({e.Message})", MethodBase.GetCurrentMethod()); } } // 转换字节 if (value is byte[] byts) { try { object retVal; TypeCode typeCode = Type.GetTypeCode(typeof(T)); switch (typeCode) { case TypeCode.Object: retVal = ObjectConvert.C2Obj <T>(byts); break; case TypeCode.String: retVal = ObjectConvert.C2Str(byts); break; case TypeCode.DateTime: retVal = ObjectConvert.C2Date(byts); break; case TypeCode.Decimal: retVal = ObjectConvert.C2Dec(byts); break; case TypeCode.Double: retVal = ObjectConvert.C2Dbl(byts); break; case TypeCode.Single: retVal = ObjectConvert.C2Flt(byts); break; case TypeCode.Int64: retVal = ObjectConvert.C2Lng(byts); break; case TypeCode.Int32: retVal = ObjectConvert.C2Int(byts); break; case TypeCode.Int16: retVal = ObjectConvert.C2Short(byts); break; case TypeCode.UInt64: retVal = ObjectConvert.C2Lng(byts); break; case TypeCode.UInt32: retVal = ObjectConvert.C2Int(byts); break; case TypeCode.UInt16: retVal = ObjectConvert.C2Short(byts); break; case TypeCode.Byte: retVal = ObjectConvert.C2Byte(byts); break; case TypeCode.SByte: retVal = ObjectConvert.C2SByte(byts); break; case TypeCode.Char: retVal = ObjectConvert.C2Chr(byts); break; case TypeCode.Boolean: retVal = ObjectConvert.C2Bool(byts); break; default: retVal = TypeConvert.C2Type <T>(byts); break; } return((T)retVal); } catch (Exception e) { throw new RedisClientException($"将结果转换成类型({typeof(T).Name})失败({e.Message})", MethodBase.GetCurrentMethod()); } } return(default);