如何在查询表达式中使用隐式类型的局部变量和数组(C# 编程指南)

每当需要编译器确定本地变量类型时,均可使用隐式类型本地变量。 必须使用隐式类型本地变量来存储匿名类型,匿名类型通常用于查询表达式中。 以下示例说明了在查询中可以使用和必须使用隐式类型本地变量的情况。

隐式类型本地变量使用 var 上下文关键字进行声明。 有关详细信息,请参阅隐式类型本地变量隐式类型数组

示例

以下示例演示必须使用 var 关键字的常见情景:用于生成一系列匿名类型的查询表达式。 在此情景中,必须使用 var 隐式类型化 foreach 语句中的查询变量和迭代变量,因为你无权访问匿名类型的类型名称。 有关匿名类型的详细信息,请参阅匿名类型

private static void QueryNames(char firstLetter)
{
    // Create the query. Use of var is required because
    // the query produces a sequence of anonymous types:
    // System.Collections.Generic.IEnumerable<????>.
    var studentQuery =
        from student in students
        where student.FirstName[0] == firstLetter
        select new { student.FirstName, student.LastName };

    // Execute the query and display the results.
    foreach (var anonType in studentQuery)
    {
        Console.WriteLine("First = {0}, Last = {1}", anonType.FirstName, anonType.LastName);
    }
}

虽然以下示例在类似的情景中使用 var 关键字,但使用 var 是可选项。 因为 student.LastName 是字符串,所以执行查询将返回一系列字符串。 因此,queryId 的类型可声明为 System.Collections.Generic.IEnumerable<string>,而不是 var。 为方便起见,请使用关键字 var。 在示例中,虽然 foreach 语句中的迭代变量被显式类型化为字符串,但可改为使用 var 对其进行声明。 因为迭代变量的类型不是匿名类型,因此使用 var 是可选项,而不是必需项。 请记住,var 本身不是类型,而是发送给编译器用于推断和分配类型的指令。

// Variable queryId could be declared by using
// System.Collections.Generic.IEnumerable<string>
// instead of var.
var queryId =
    from student in students
    where student.Id > 111
    select student.LastName;

// Variable str could be declared by using var instead of string.
foreach (string str in queryId)
{
    Console.WriteLine("Last name: {0}", str);
}

另请参阅