【问题标题】:No overload for method 'ToDictionary' takes 0 arguments方法 'ToDictionary' 没有重载需要 0 个参数
【发布时间】:2016-04-21 08:29:11
【问题描述】:

实际上我应该工作,从我的角度来看,我不知道有什么问题,问题是itemvalue没有ToDictionary()

也许你可以看看?!

方法签名: public static IDictionary<string, object> ListO(this object instance)

我的代码:

 if (instance == null)
                throw new NullReferenceException();

            var result = instance as IDictionary<string, object>;
            if (result != null)
                return result;

            return instance.GetType()
                .GetProperties()
                .ToDictionary(x => x.Name, x =>
                {
                    object value = x.GetValue(instance);

                    if (value != null)
                    {
                        var valueType = value.GetType();

                        // Whe should manually check for string type because IsPrimitive will return false in case of string
                        if (valueType.IsPrimitive || valueType == typeof(string))
                        {

                            return value;
                        }
                        else if (valueType.GetInterfaces().Any(t => t == typeof(IEnumerable)))
                        {
                            List<object> elements = new List<object>();

                            foreach (var item in value as IEnumerable)
                            {
                                elements.Add(item.ToDictionary());//problem here
                            }

                            return elements;
                        }
                        else
                        {
                            return value.ToDictionary();//problem here
                        }

                    }
                    return null;
                }); 

我明白了:

方法 'ToDictionary' 没有重载需要 0 个参数

我做错了什么?

【问题讨论】:

  • 1) 尝试在单个项目上使用 ToDictionary() 2) 使用来自 ToDictionary 的不存在的方法签名。
  • 你到底想做什么?你期待这些是字典吗?或者这些是您想要转换为字典的 IEnumerable?
  • 该方法应该将属性名称读取为字符串,并将其值读取为对象,基于反射,有时给定的对象可以具有列表或其他类型的子对象,这是该方法应该注意的.它应该将给定的对象返回给字符串(属性名称),并将其值作为对象返回
  • 为什么不直接var dict = instance.GetType().GetProperties().ToDictionary(x =&gt; x.Name, x =&gt; x.GetValue(instance));

标签: c# generics lambda


【解决方案1】:
elements.Add(item.ToDictionary(e => e.Key,e => e.Value))

【讨论】:

  • 虽然此代码 sn-p 可能会解决问题,但including an explanation 将帮助人们了解您的代码建议的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多