隐式类型变量(var)
var
关键字允许程序员在编译时隐式键入变量。var
声明与显式声明的变量具有相同的类型。
var squaredNumber = 10 * 10;
var squaredNumberDouble = 10.0 * 10.0;
var builder = new StringBuilder();
var anonymousObject = new
{
One = SquaredNumber,
Two = SquaredNumberDouble,
Three = Builder
}
上述变量的类型分别为 int
,double
,StringBuilder
和匿名类型。
值得注意的是,var
变量不是动态类型的。SquaredNumber = Builder
无效,因为你正在尝试将 int
设置为 StringBuilder
的实例