public TK Get <TK>(Expression <Func <T, object> > key, CultureInfo cultureInfo = null) { var value = this[key]; if (value == null || String.IsNullOrEmpty(value.ToString())) { return(default(TK)); } if (value.ToString().IsJson()) { return(Serializer.Deserialize <TK>(value.ToString())); } // https://msdn.microsoft.com/en-us/library/system.componentmodel.typedescriptor(v=vs.110).aspx TypeConverter converter = TypeDescriptor.GetConverter(typeof(TK)); try { return((TK)converter.ConvertFromString(null, cultureInfo ?? CultureInfo.CurrentCulture, value.ToString())); } catch (Exception) { return(default(TK)); } }
/// <summary> /// Maps redis values array into our generic model /// </summary> /// <param name="values"></param> /// <returns></returns> private T Map(RedisValue[] values) { // redis properties count must match count of object properties // in order to get right property result for corresponding property var properties = typeof(T).GetProperties(); if (properties.Count() != values.Count()) { throw new ArgumentException("Object properties not matching"); } dynamic obj = new ExpandoObject(); var expandoDict = obj as IDictionary <string, object>; for (int i = 0; i < properties.Count(); i++) { var redisValue = values[i]; var property = properties.ElementAt(i); if (!redisValue.HasValue) { expandoDict[property.Name] = null; } if (redisValue.IsJson()) { expandoDict[property.Name] = Serializer.Deserialize <dynamic>(redisValue.ToString()); } else { expandoDict[property.Name] = redisValue.ToString(); } } string serializedObject = Serializer.Serialize(obj); return(Serializer.Deserialize <T>(serializedObject)); }