Compiler Error CS1941

“clause”子句中一个表达式的类型不正确。类型推理在对“method”的调用中失败。

查询表达式中的类型推理源于数据源中的元素类型。

更正此错误

  1. 如果发生此错误的原因不十分明显,请仔细检查查询,并跟踪从数据源到错误发生点的每个子句的结果的类型。

下面的代码生成 CS1941,因为 equals 运算符被要求对 intstring 进行比较。

// cs1941.cs
using System.Collections;
using System.Linq;
class Test
{
    static int Main()
    {
        var nums = new[] { 1, 2, 3, 4, 5, 6 };
        var words = new string[] { "lake", "mountain", "sky" };
        IEnumerable e = from n in nums
                        join w in words on n equals w // CS1941
                        select w;
        return 0;
    }
}

发生类型推理失败的方法是查询子句在编译时转换为的方法。

请参阅

LINQ 查询表达式(C# 编程指南)

Type Relationships in LINQ Query Operations (C#)