当前位置:网站首页>C# - var 关键字
C# - var 关键字
2022-08-08 08:40:00 【wumingxiaoyao】
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 */
边栏推荐
- 22-08-06 Xi'an EasyExcel implements dictionary table import and export
- 力扣142-环形链表——链表&快慢指针法&哈希表法
- Go 匿名字段与实现重写方法
- shell循环语句
- DBeaver 22.1.4 发布,可视化数据库管理平台
- 【回归预测】基于GPML工具箱的高斯过程回归附matlab代码
- lua --- 基本语法学习
- The basic method of use in the volatile in the C language
- idea big data tools submit flink tasks
- 关于 QtCreator使用msvc2017x64编译器编译项目报错”编译器的堆空间不足“错误 的解决方法
猜你喜欢
随机推荐
jupyter lab内终端从sh变为bin/bash(切换conda操作)
【收藏】3. 壁纸收藏
斯坦福21秋季:实用机器学习【第5章】
DBeaver 22.1.4 released, a visual database management platform
sed命令
选择适合投稿的英文期刊或会议的方法
你真的了解IP地址吗?
[Regression prediction] Gaussian process regression based on GPML toolbox with matlab code
信息学奥赛一本通 1923:【03NOIP普及组】数字游戏 | 洛谷 P1043 [NOIP2003 普及组] 数字游戏
百度飞浆EISeg高效交互式标注分割软件的使用教程
docker部署redis容器问题
LeetCode:第305场周赛【总结】
Go 函数与方法
Stanford Fall 21: Practical Machine Learning [Chapter 5]
看顶级测工怎么玩转Apifox接口测试工具
文献学习(part33)--Clustering by fast search and find of density peaks
方案 | 医疗单据OCR识别,为医保零星报销打造安全屏障
php生成二维码并下载图片(适应于框架)
Excel中text函数5中常用方法
手机APP测试流程规范和方法你知道多少?








