方法签名:无法转换lambda表达式键入 'System.Collections.Generic.IEqualityComparer <string>',因为它不是一个委托类型
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
。
这是什么东西?
好的,我更新了代码。
是您的实际代码不完整呢?如果是这样,缺少返回值可能会混淆ToDictionary的两个重载之间的类型推断,这两个重载需要三个参数。 – Lee
还要确保将返回类型转换为'object',例如:'x => {return(object)x.PropertyType; }} –
代替'x => {}'write'x => GetValue(instance)' –