var i = 5; var str = “Csharp” var numbers = new int[]{1,2,3}; var orders = new System.Collections.Hashtable(); var orders1 = new Dictionary();
var i = xxx ; 的作用就是用 xxx 的类型声明为i的类型。并给i 赋值。 由于声明时候,需要依赖于等号右边的表达式,所以必须同时赋值。否则下面的书写就会报错误: Error Implicitly typed locals must be initialized var gg;
使用 Implicitly typed local variables 时应遵守下列约束: 1. The declarator must include an initializer 声明时必须包含初始化器。
2、The initializer must be an exPRession. The initializer cannot be an object or collection initializer by itself, but it can be a new expression that includes an object or collection initializer. 初始化必须是一个表达式。初始化表达式不能包含它自身, 但是可以是包含一个对象或集合初始化器的一个new表达式(即匿名类型)。
3、The compile-time type of the initializer expression cannot be the null type. 初始化器表达式的编译期类型不可以是空(null)类型。 比如: var gg = null; 这行代码就会报错误: Cannot assign '' to an implicitly typed local
4、If the local variable declaration includes multiple declarators, the initializers must all have the same compile-time type. 如果局部变量声明包含了多个声明符,这些声明符必须具备同样的编译期类型。 比如如下代码: