这意味着将由编译器推断要声明的本地类型:
// This statement:var foo = "bar";// Is equivalent to this statement:string foo = "bar";
值得注意的是,
var并未将变量定义为动态类型。因此,这是不合法的:
var foo = "bar";foo = 1; // Compiler error, the foo variable holds strings, not ints
var只有两个用途:
- 它需要较少的类型来声明变量,尤其是在将变量声明为嵌套的泛型类型时。
- 在存储对匿名类型的对象的引用时,必须使用它,因为类型名称无法事先知道:
var foo = new { Bar = "bar" };
var除了本地语言,您不能将其用作任何其他类型。因此,您不能使用关键字
var来声明字段/属性/参数/返回类型。



