是的,绝对的 - 因为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)
| 归档时间: |
|
| 查看次数: |
86 次 |
| 最近记录: |