NET/C#中的匿名类型 var关键字
上一篇 /
下一篇 2013-10-15 20:26:13
/ 个人分类:C#
var(C# 参考)
从 Visual C# 3.0 开始,在方法范围中声明的变量可以具有隐式类型 var。 隐式类型的本地变量是强类型变量(就好像您已经声明该类型一样),但由编译器确定类型。 下面的两个 i 声明在功能上是等效的:
var i = 10; // implicitly typed
int i = 10; //explicitly typed
有关更多信息,请参见隐式类型的局部变量(C# 编程指南)和 LINQ 查询操作中的类型关系 (C#)。
下面的示例演示了两个查询表达式。 在第一个表达式中,允许但不需要使用 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);
}
相关阅读:
- 自动化测试与自动化测试生命周期 (573702881, 2008-4-13)
- 软件测试的基础知识概要介绍 (卧龙公子, 2008-10-30)
- 性能测试基础问答题 (leojuan, 2008-12-09)
- 嵌入式系统设计师之嵌入式系统基础知识 (coffeetea2008, 2009-2-17)
- JAVA基础知识精华总结 (smile665, 2010-5-22)
- Java面试题--基础知识部分 (smile665, 2010-5-22)
- oracle 基础 (weixiaoyeah, 2010-6-07)
- 什么是白盒测试,什么是黑盒测试…… (feihongren, 2012-2-24)
- 关于面试测试的题目和答案(转载) (wangsf110, 2013-7-27)
- NET/C#中的匿名类型 (gqy0923, 2013-10-15)
收藏
举报
TAG:
基础知识