一、VAR 是3.5新出的一个定义强类型方式定义变量完全一样。
四 、var 关键字的常见用途是用于构造函数调用表达式。
使用 var则不能在变量声明和对象实例化中重复类型名称,如下面的示例所示:
var xs = new List<int>();
new 表达式作为替代方法:
List<int> xs = new();
List<int>? ys = new();
请注意,在示例 #2 中,foreach 迭代变量 item 必须也为隐式类型。
// 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;
// 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);
}
本文转载于:https://wenda.so.com/q/1378644256068714