2016-04-21 172 views
0

方法签名:无法转换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

这是什么东西?

好的,我更新了代码。

+0

是您的实际代码不完整呢?如果是这样,缺少返回值可能会混淆ToDictionary的两个重载之间的类型推断,这两个重载需要三个参数。 – Lee

+0

还要确保将返回类型转换为'object',例如:'x => {return(object)x.PropertyType; }} –

+0

代替'x => {}'write'x => GetValue(instance)' –

回答

0

问题是ToDictionary需要一个IEqualityComparer作为第二个参数,并且您提供的内容没有实现该接口。

你有如何在下面的链接中使用此梅托德一个解释:http://www.dotnetperls.com/todictionary

+0

还有一个超载,期望两个提取表达式,一个用于键,一个用于该值。这显然是操作者想要使用的,但是他没有正确实现它,所以编译器无法推断出正确的过载。 – derpirscher

相关问题