【问题标题】:Redis Get HashSet into desired type not working with nullable typeRedis 将 HashSet 转换为所需的类型,不适用于可空类型
【发布时间】:2016-12-26 16:15:43
【问题描述】:

我已经通过以下方法将我的类值插入到 redis 中

 public static bool InsertHashItem(string key, object obj)
        {
            bool result = false;
            try
            {
                if (Muxer != null && Muxer.IsConnected && Muxer.GetDatabase() != null)
                {
                    IDatabase getDatabase = Muxer.GetDatabase();
                    getDatabase.HashSet(key, ToHashEntries(obj));
                    result = true;
                }
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex.Message, ex);
            }
            return result;
        }

我的班级看起来像

  public class TestType
    {
        public int telcoid { get; set; }
        public int parent_id { get; set; }
        public string checksum { get; set; }
        public string tag_registration_id { get; set; }
        public string market_id { get; set; }
        public double amount { get; set; }
        public string utid { get; set; }
        public int status { get; set; }

        public DateTime? dt { get; set; }

    }

现在为了获得那个类,我编写了一个在可空类型上失败的方法

 public static T GetHashItem<T>(string key) where T : new()
        {
            T obj = default(T);

            try
            {
                if (Muxer != null && Muxer.IsConnected && Muxer.GetDatabase() != null)
                {
                    IDatabase getDatabase = Muxer.GetDatabase();
                    var hashkey = getDatabase.HashKeys(key);
                    if (hashkey != null && hashkey.Count() > 0)
                    {
                        var dic = hashkey.ToDictionary(k => k, k => getDatabase.HashGet(key, k));

                        obj = new T();
                        foreach (var prop in typeof(T).GetProperties())
                        {


                            prop.SetValue(obj, Convert.ChangeType(dic[prop.Name], prop.PropertyType));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex.Message, ex);
            }
            return obj;
        }

请告知我需要什么更正

【问题讨论】:

    标签: c#-4.0 redis .net-4.5 system.reflection stackexchange.redis


    【解决方案1】:

    尝试获取底层类型,当属性类型为 Nullable 时,像这样:

    Type type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
    prop.SetValue(obj, Convert.ChangeType(dic[prop.Name], type));
    

    【讨论】:

    • 谢谢。尝试过但有点不同。但现在会试试你推荐的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多