var的一些理解

var 是 variable(变量,可变物)的简写。在多种编程语言中,var 被用作定义变量的关键字,在一些操作系统中也能见到它的身影。类似object,但是效率比object高一点。

var是一个局部变量,也是一种强类型的定义变量,可以代替任何类型。在用var定义一个变量之后,就不允许在下文中修改此值,就像string类型的不可变特性一样。

关于var的使用,在定义非基本类型的时候使用var是一个很好的方法。

从 Visual C# 3.0 开始,在方法范围中声明的变量可以具有隐式类型 var。 隐式类型的本地变量是强类型变量(就好像您已经声明该类型一样),但由编译器确定类型。 下面的两个 i 声明在功能上是等效的:

var i = 10; // implicitly typed
int i = 10; //explicitly typed
实例:

下面的示例演示了两个查询表达式。 在第一个表达式中,允许但不需要使用 var,因为可以将查询结果的类型显式声明为IEnumerable<string>。 但是,在第二个表达式中必须使用 var,因为结果是一个匿名类型集合,而该类型的名称只有编译器本身可以访问。 请注意,在第二个示例中,foreach 迭代变量 item 也必须转换为隐式类型。


 
// Example #1: var is optional because
// 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;

// 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);
}

// Example #2: var is required because
// the select clause specifies an anonymous type
var custQuery = from cust in customers
                where cust.City == "Phoenix"
                select new { cust.Name, cust.Phone };

// var must be used because each item 
// in the sequence is an anonymous type
foreach (var item in custQuery)
{
    Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone);
}
posted @ 2016-11-04 12:31  Zy宇  阅读(1613)  评论(0编辑  收藏  举报