【发布时间】:2016-04-21 08:29:11
【问题描述】:
实际上我应该工作,从我的角度来看,我不知道有什么问题,问题是item和value没有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 => x.Name, x => x.GetValue(instance));?