使用 Var 类型的成员

本文关键字:成员 类型 Var 使用 | 更新日期: 2023-09-27 17:53:53

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

使用 Var 类型的成员

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

所以例如:

var text = "this is a string";
Console.WriteLine(text.Length); // Uses string.Length property

除了方便之外,引入了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.

将其与 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

如果使用 var ,则必须立即初始化变量。例:

var a = 1;

这告诉编译器它是一个整数。但是,如果您不初始化,则编译器不知道它应该使用哪种类型。

var b;

b是什么类型?

这同样适用于类的成员。

var只是一个方便的功能,因此您不必键入类的名称或完全限定的命名空间。