C# 3.0 feature 1--Implicitly typed local variables


我们来看下列变量声明

var i=5;
   var numbers
=new int[]{1,2,3};

首先,C# compiler 会在同一个namespace范围内寻找用户自定义的var类型,如果找到,则把i, numbers做作var类型处理。如果没找到,则认为i, numbers为implicitly typed local variables,并根据其初始值确实其类型,上述代码的IL代码和下列代码的IL相同

int i=5;
   int[] numbers=new int[]{1,2,3};

使用Implicitly typed local variables时应遵守下列约束:
   1. The declarator must include an initializer
   2. The initializer must be an expression
   3. The initializer expression must have a complie-time type which cannot be the null type.
   4. The local variable declaration cannot include multiple declarations.
   5. The initializer cannot refer to itself.
  
粗一看,额的神啊,一共有五条约束,还挺麻烦的,其实归纳下来主要就一句话,必须要让编绎器能从initializer准确推断出变量的类型,编绎器也是人啊,它需要根据推断出来的类型为变量分配内存空间。
比如: var x = {1,2,3} //error, cannot infer the type from {1,2,3"}
              var x = new int[]{1,2,"3}; // right. x is an array of type integer

最后说一下Implicitly typed local variable的使用范围,它可不是到处能用。仅仅可以用于下面四种情况
   1. 局部变量声明
   2. for 语句中变量声明)
   3. using 语句初始化变量时.
   4. foreach 中iterator类型声明)

posted @ 2007-04-16 17:45  芭蕉  阅读(404)  评论(1编辑  收藏  举报