方法签名:
public static IDictionary<string, object> ListX(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;
}
// If the value type is enumerable then we iterate over and recursively call ToDictionary on each item
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());
}
return elements;
}
// The value type is a complex type so we recursively call ToDictionary
else
{
return value.ToDictionary();
}
}
return null;
});
对于x
,我得到Cannot convert lambda expression to type 'System.Collections.Generic.IEqualityComparer<string>' because it is not a delegate type
。
这里的问题是什么?
好的,我更新了该代码。
答案 0 :(得分:0)
问题是ToDictionary期望IEqualityComparer作为第二个参数,而你提供的不会实现该接口。
您在以下链接中获得了有关如何使用此metod的说明:http://www.dotnetperls.com/todictionary