C#3.0 为我们带来什么(4) —— 具有隐式类型的局部变量var

it2022-05-05  113

C#3.0 为我们带来什么(4) —— 具有隐式类型的局部变量var

在c#3.0里允许我们这样定义变量 var age = 10; var name = "james"; var time = DateTime.Now; var books = new string[]{"aa","bb"}; 但是也仅此而已,var只允许我们定义c#编译器通过上下文推断出类型的变量。 var x;                 // 错误,没有用来推断类型的初始化器 var y = { 1, 2, 3 };  // 错误,不允许使用集合初始化器 var z = null;        // 错误,不允许出现空类型 像这样也是不允许的 var a= 10; a= "james"; 来看看隐私类型的IL实现。 c#2.0.method public hidebysig instance void  oldvar() cil managed {   // 代码大小       8 (0x8)   .maxstack  1   .locals init ([0] string name)   IL_0000:  nop   IL_0001:  ldstr      "james"   IL_0006:  stloc.0   IL_0007:  ret } // end of method testvar::oldvar c#3.0.method public hidebysig instance void  newvar() cil managed {   // 代码大小       8 (0x8)   .maxstack  1   .locals init ([0] string name)   IL_0000:  nop   IL_0001:  ldstr      "james"   IL_0006:  stloc.0   IL_0007:  ret } // end of method testvar::newvar完全一样。 我猜想var的出现其实完全是为了配合匿名类型而出现的。

            var a  =   new   { Name = "james" ,Age = 25} ;            Console.WriteLine(a.Name);            Console.WriteLine(a.Age);

在linq中应用也比较多

int [] numbers  =   5413986720 } ;var queryLowNums  =     from num  in  numbers     where  num  <   5     select num; foreach  (var s  in  queryLowNums) {    Console.Write(s.ToString() + " ");} 也就是说对象是匿名类型,或者对象是难以预测的类型的时候。 像这样的代码var age = 10;还是少写为好,一是类型安全,再是也为代码阅读尽量少造成障碍。 posted on 2008-01-06 18:20 tianyamoon 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/tianyamoon/archive/2008/01/06/1027994.html

相关资源:C#特性 匿名类型与隐式类型局部变量使用介绍

最新回复(0)