C# - var 关键字

引言

C# 代码经常会看到 var 关键字定义一个变量,带点神秘色彩,今天就来揭秘一下。

从 C# 3.0 开始,在方法范围内声明的变量可以具有隐式“类型” var。 隐式类型本地变量为强类型,就像用户已经自行声明该类型,但编译器决定类型一样。

var 关键字使用规则

如果编译器可以从初始化表达式推断类型,我们可以使用关键字 var 来声明变量类型,推断类型可以是内置类型、匿名类型、用户定义类型或 .NET 类库中定义的类型。

举例: i 的以下两个声明在功能上是等效的:
var i = 10;
var 关键字隐藏了 i 的类型,在编译时,会根据右边的值的类型来确定 i 的类型是 int。

var i = 10; // Implicitly typed.
int i = 10; // Explicitly typed.

隐式类型变量是静态类型的,也就是一旦确定类型就不能更改类型,但你可以更改成相同类型的值。
例如:下面操作,编译会出错
Cannot implicitly convert type 'type' to 'type'

var i = 10;
 i = "a";

var 只能用来定义方法内的局部变量,如果定义在其它范围(如:类的字段),会有编译错误 The contextual keyword 'var' may only appear within a local variable declaration.

var 在表达式中的应用

例 1 :var 可以选

var 的使用是允许的,但不是必需的,因为查询结果的类型可以明确表述为 IEnumerable< string > 。

  IEnumerable<string> wordQuery = from word in words
                            where word[0] == 'g'
                            select word;
                            
// Because each element in the sequence is a string,
// not an anonymous type, var is optional here also.
foreach (string s in wordQuery)
{
    
    
    Console.WriteLine(s);
}                            

但用 var 更简洁,只是一种语法便利,比如,有时类名太长,用 var 更合适,可以偷懒敲长长的类名。

// Example #1: var is optional when
// the select clause specifies a string
string[] words = {
    
     "apple", "strawberry", "grape", "peach", "banana" };
var wordQuery = from word in words
                where word[0] == 'g'
                select word;

例 2:var 必要

在使用匿名类型初始化变量时,如果需要在以后访问对象的属性,则必须将变量声明为 var。 这是 LINQ 查询表达式中的常见方案。

从源代码角度来看,匿名类型没有名称。 因此,如果使用 var 初始化了查询变量,则访问返回对象序列中的属性的唯一方法是在 foreach 语句中将 var 用作迭代变量的类型。

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
 */

猜你喜欢

转载自blog.csdn.net/wumingxiaoyao/article/details/126213443#comments_22762280
今日推荐