当前位置:网站首页>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 */
边栏推荐
猜你喜欢
DVWA full level detailed customs clearance tutorial
22-08-06 Xi'an EasyExcel implements dictionary table import and export
Today share how to submit a bug
Offensive and defensive world - leaking
攻防世界——ics-05
Matlab实现异构交通流
推荐下载软件
【office】word
【回归预测】基于GPML工具箱的高斯过程回归附matlab代码
Raspberry pie 】 【 without WIFI even under the condition of the computer screen
随机推荐
攻防世界——ics-05
Kotlin协程:生命周期原理
攻防世界——lottery
DBeaver 22.1.4 released, a visual database management platform
oracle sql语法 更改为mysql sql语法 或者代码实现
数据治理(三):数据质量管理
idea big data tools submit flink tasks
What exactly happens after entering the URL in the browser?
【图像分类】2021-CoAtNet NeurlPS
Matlab实现异构交通流
67:第五章:开发admin管理服务:20:开发【解冻/冻结用户,接口】;(用户状态变更后,需要刷新用户状态,即变更用户会话信息:我们一般通过“删除redis中会话信息,强制用户重新登录“来做的;)
Golang实现sha256或sha512加密
数据库_JDBC
【Enumeration】Continuous factor
六十分之七——焦虑路上的涅槃
推荐下载软件
Database_JDBC
分清成员函数非成员函数和友元函数
【优化调度】基于粒子群实现并网模型下微电网的经济调度优化附matlab代码
我的MySQL安装这样了怎么解决也