使用Var类型的成员

sal*_*l87 -3 c# var

在使用var关键字声明隐式类型的对象之后,是否可以使用特定于编译器在任何其他语句中分配给它的类型的成员,方法或属性?

Jon*_*eet 6

是的,绝对的 - 因为var实际上并不是一种类型.它只是告诉编译器:"我不打算明确地告诉你类型 - 只需使用赋值运算符的右侧操作数的编译时类型来计算变量的类型."

例如:

var text = "this is a string";
Console.WriteLine(text.Length); // Uses string.Length property
Run Code Online (Sandbox Code Playgroud)

除了方便之外,var还引入了匿名类型,您无法明确声明变量类型.例如:

// The type involved has no name that we can refer to, so we *have* to use var.
var item = new { Name = "Jon", Hobby = "Stack Overflow" };
Console.WriteLine(item.Name); // This is still resolved at compile-time.
Run Code Online (Sandbox Code Playgroud)

将此与dynamic编译器基本上推迟使用成员直到执行时间进行比较,以基于执行时类型绑定它们:

dynamic foo = "this is a string";
Console.WriteLine(foo.Length); // Resolves to string.Length at execution time

foo = new int[10]; // This wouldn't be valid with var; an int[] isn't a string
Console.WriteLine(foo.Length); // Resolves to int[].Length at execution time

foo.ThisWillGoBang(); // Compiles, but will throw an exception
Run Code Online (Sandbox Code Playgroud)