【问题标题】:Linq Cannot implicitly convert typeLinq 无法隐式转换类型
【发布时间】:2013-09-21 21:26:06
【问题描述】:

我是 Linq 语法的新手,遇到错误

“无法将类型'System.Collections.Generic.IEnumerable<System.Reflection.MethodInfo>'隐式转换为'System.Collections.Generic.IEnumerable<System.Reflection.MethodBase>'。存在显式转换(您是否缺少强制转换?)”

在我的应用程序的以下行

 IEnumerable<MethodBase> methods = 
                    from p in defaultMembers.OfType<PropertyInfo>()
                    select p.GetGetMethod() into m
                    where m != null
                    select m;

有什么想法吗?谢谢

【问题讨论】:

  • 您的代码运行良好。你确定那是导致问题的线路吗?
  • 我正在处理一些其他代码,当我在 .net 框架 4.0 中构建它时,它构建得很好,但在 3.5 中没有构建,并且出现上述错误
  • 好的,我知道问题出在哪里了。 IEnumerable&lt;T&gt; 在 .NET 3.5 中不是协变的

标签: c# asp.net linq


【解决方案1】:

问题是 IEnumerable&lt;T&gt; 在 .NET 3.5 中不是协变的(它在 .NET4+ 中)。这就是为什么你不能将IEnumerable&lt;ChildClass&gt; 分配给IEnumerable&lt;ParentClass&gt;。

更改您的变量声明以完全匹配查询结果(使用var 和隐式类型变量或指定正确的类型):

 IEnumerable<MethodInfo> methods = 
                    from p in defaultMembers.OfType<PropertyInfo>()
                    select p.GetGetMethod() into m
                    where m != null
                    select m;

或者如果你真的需要 IEnumerable&lt;MethodBase&gt; 在你的查询中添加额外的演员:

 IEnumerable<MethodBase> methods = 
                    from p in defaultMembers.OfType<PropertyInfo>()
                    select p.GetGetMethod() into m
                    where m != null
                    select (MethodBase)m;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多