C#隐含类型局部变量

参见MSDN

从Visual C# 3.0开始,在方法体内可以声明隐式的变量类型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<Customer>
// or perhaps IQueryable<Customer>
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<int>                             
var list = new List<int>();
需要了解的一点是, var 关键字并不意味着“变体”,也不表示该变量是松散类型化变量或后期绑定变量。 它只是表示由编译器确定和分配最适当的类型。

var 关键字可在以下情况中使用:

  • 在如上所示的局部变量上。
  • 在 for 初始化语句中。

for(var x = 1; x < 10; x++)
  • 在foreach初始化语句中。
foreach(var item in list){...}
using (var file = new StreamReader("C:\\myfile.txt")) {...}


var 和匿名类型

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

从源代码的角度来说,匿名类型没有名称。因此,如果已使用 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,因为null就像lambda表达式或者方法一样没有类型。但是,可以被初始化为一个得到null值的表达式,只要这个表达式有类型。
  • var不能用作类的字段
  • var类型声明的变量不能用作自己初始化的表达式中,换言之,var v=v++;将会在编译时报错
  • 复合的隐式类型不能被同时初始化
  • 如果在作用域中,我们定义了一个var类型的变量,尝试用var关键字初始化一个局部变量,编译时会报错。
  • 使用 var 可能使其他开发人员更加难以理解您的代码。

猜你喜欢

转载自blog.csdn.net/u011704031/article/details/17070109