隐式类型的局部变量

可以赋予局部变量推断“类型”var 而不是显式类型。var 关键字指示编译器根据初始化语句右侧的表达式推断变量的类型。推断类型可以是内置类型、匿名类型、用户定义类型或 .NET Framework 类库中定义的类型。

下面的示例演示了使用 var 声明局部变量的各种方式:

// i is compiled as an int
var i = 5;
 
// s is compiled as a string
var s = "Hello";
 
// a is compiled as int[]
var a = new[] { 0, 1, 2 };
 
// expr is compiled as IEnumerable
// or perhaps IQueryable
var expr =
    from c in customers
    where c.City == "London"
    select c;
 
// anon is compiled as an anonymous type
var anon = new { Name = "Terry", Age = 34 };
 
// list is compiled as List
var list = new List();

需要了解的一点是,var 关键字并不意味着“变体”,也不表示该变量是松散类型化变量或后期绑定变量。它只是表示由编译器确定和分配最适当的类型。

var 关键字可在下面的上下文中使用:

在如上示例所示的局部变量(在方法范围中声明的变量)上。

在 for 初始化语句中。

for(var x = 1; x < 10; x++)

在 foreach 初始化语句中。

foreach(var item in list){...}

在 using 语句中

using (var file = new StreamReader("C:\\myfile.txt")) {...}

有关更多信息,请参见如何:在查询表达式中使用隐式类型的局部变量和数组(C# 编程指南)。

var 和匿名类型
在很多情况下,var 是可选的,它只是提供了语法上的便利。但是,在使用匿名类型初始化变量时,如果需要在以后访问对象的属性,则必须将该变量声明为 var。这在 LINQ 查询表达式中很常见。有关更多信息,请参见匿名类型(C# 编程指南)。

从源代码的角度来说,匿名类型没有名称。因此,如果已使用 var 初始化查询变量,则只有一种方法可以访问返回的对象序列中的属性,那就是使用 var 作为 foreach 语句中的迭代变量的类型。

class ImplicitlyTypedLocals2
{
    static void Main()
    {
        string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" };
 
        // If a query produces a sequence of anonymous types,
        // then use var in the foreach statement to access the properties.
        var upperLowerWords =
             from w in words
             select new { Upper = w.ToUpper(), Lower = w.ToLower() };
 
        // Execute the query
        foreach (var ul in upperLowerWords)
        {
            Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower);
        }
    }
}
/* Outputs:
    Uppercase: APPLE, Lowercase: apple
    Uppercase: BLUEBERRY, Lowercase: blueberry
    Uppercase: CHERRY, Lowercase: cherry
 */

备注
下列限制适用于隐式类型的变量声明:

只有在同一语句中声明和初始化局部变量时,才能使用 var;不能将该变量初始化为 null、方法组或匿名函数。

不能将 var 用于类范围的域。

由 var 声明的变量不能用在初始化表达式中。换句话说,表达式 int i = (i = 20) 是合法的;但表达式 var i = (i = 20) 则会产生编译时错误。

不能在同一语句中初始化多个隐式类型的变量。

如果范围中有一个名为 var 的类型,则 var 关键字将解析为该类型名称,而不作为隐式类型局部变量声明的一部分进行处理。

在查询表达式中,当难以确定查询变量的确切构造类型时,您会发现 var 也很有用。这种情况可能发生在分组和排序操作中。

当在键盘上键入变量的具体类型单调乏味时,或者当该类型显而易见或对提高代码可读性没有作用时,var 关键字也可能有用。var 以这种方式发挥作用的一个示例是嵌套的泛型类型,例如在分组操作中使用的那些类型。在下面的查询中,查询变量的类型是 IEnumerable>。只要您和其他必须维护您代码的人员了解到这一点,就可以毫无问题地使用隐式类型化,以达到方便和简洁的效果。

// Same as previous example except we use the entire last name as a key.
// Query variable is an IEnumerable>
 var studentQuery3 =
     from student in students
     group student by student.Last;

不过,使用 var 确实可能使其他开发人员更加难以理解您的代码。因此,C# 文档通常仅在需要时才使用 var。

This entry was posted in ASP.NET and tagged , . Bookmark the permalink.

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word