【问题标题】:C# compilation error with LINQ and dynamic inheritanceLINQ 和动态继承的 C# 编译错误
【发布时间】:2014-12-16 22:08:57
【问题描述】:

考虑下面的代码(为了这个测试,它没有做任何特别的用途——它只是为了演示发生的错误)

Dictionary<string, dynamic> d = new Dictionary<string, dynamic>()
{
    { "a", 123 },
    { "b", Guid.NewGuid() },
    { "c", "Hello World" }
};
d.Where(o => o.Key.Contains("b")).ForEach(i => Console.WriteLine(i.Value));
//retuns the Guid value, as expected.

我想用继承包装Dictionary&lt;string, dynamic&gt;

public class CustomDictionary : Dictionary<string, dynamic>
{
}

这是上面使用这个派生类的例子:

CustomDictionary d = new CustomDictionary()
{
    { "a", 123 },
    { "b", Guid.NewGuid() },
    { "c", "Hello World" }
};
d.Where(o => o.Key.Contains("b")).ForEach(i => Console.WriteLine(i.Value));

发生这种情况...

关于导致问题的原因或如何解决问题的任何想法?

【问题讨论】:

标签: c# linq inheritance compiler-errors


【解决方案1】:

我相信我已经缩小了与 Linq Where 扩展方法的绑定范围。

这行得通:

   d.AsEnumerable()
    .Where(o => o.Key.Contains("b"))
    .ToList()
    .ForEach(i => Console.WriteLine(i.Value));

这有效(静态调用扩展方法):

Enumerable.Where(d.AsEnumerable(),o => o.Key.Contains("b"))
          .ToList()
          .ForEach(i => Console.WriteLine(i.Value));

但事实并非如此:

   d.Where(o => o.Key.Contains("b"))
    .ToList()
    .ForEach(i => Console.WriteLine(i.Value));

如果我在没有AsEnumerable()的情况下调用静态扩展方法:

Enumerable.Where(d,o => o.Key.Contains("b"))
          .ToList()
          .ForEach(i => Console.WriteLine(i.Value));

我得到更好的编译器错误:

参数 1:无法从 'UserQuery.CustomDictionary' 转换为 'System.Collections.Generic.IEnumerable&lt;System.Collections.Generic.KeyValuePair&lt;string,dynamic&gt;&gt;'

所以由于某种原因,编译器无法将继承的类绑定到扩展方法。

以下方法也有效:

  • d 显式转换为IEnumerable&lt;System.Collections.Generic.KeyValuePair&lt;string,dynamic&gt;&gt;
  • 使用object 代替dynamic

【讨论】:

    猜你喜欢
    • 2011-03-27
    • 2018-05-07
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    相关资源
    最近更新 更多