如何初始化var?

maz*_*ztt 56 c# initialization

我可以用null或一些空值初始化var吗?

thi*_*eek 54

C#是一种严格/强类型的语言.var是为匿名类型引入的编译时类型绑定,但您可以将var用于在设计时已知的原始类型和自定义类型.在运行时,没有像var这样的东西,它被实际类型替换,它是一个引用类型或值类型.

当你说,

var x = null; 
Run Code Online (Sandbox Code Playgroud)

编译器无法解析此问题,因为没有绑定到null的类型.你可以这样做.

string y = null;
var x = y;
Run Code Online (Sandbox Code Playgroud)

这将起作用,因为现在x可以在编译时知道它的类型,在这种情况下是字符串.


naw*_*fal 31

好吧,正如其他人所说,类型的模糊是问题.所以答案是否定的,C#不会让它发生,因为它是一种强类型语言,它只处理编译时已知的类型.编译器本来可以设计为推断类型object,但设计者选择避免额外的复杂性(在C#null中没有类型).

一种选择是

var foo = new { }; //anonymous type
Run Code Online (Sandbox Code Playgroud)

再次注意,您正在初始化为已知类型的编译时间,并且最后它不是null,而是匿名对象.它只比短几行new object().您只能foo在这种情况下重新分配匿名类型,这可能是也可能不是.

初始化为null不知道的类型是不可能的.

除非你正在使用dynamic.

dynamic foo = null;
//or
var foo = (dynamic)null; //overkill
Run Code Online (Sandbox Code Playgroud)

当然,除非你想将值重新赋值给foo变量,否则它是没用的.您在Visual Studio中也失去了智能感知支持.

最后,正如其他人已经回答的那样,你可以通过强制转换声明一个特定的类型;

var foo = (T)null;
Run Code Online (Sandbox Code Playgroud)

所以你的选择是:

//initializes to non-null; I like it; cant be reassigned a value of any type
var foo = new { }; 

//initializes to non-null; can be reassigned a value of any type
var foo = new object();

//initializes to null; dangerous and finds least use; can be reassigned a value of any type
dynamic foo = null;
var foo = (dynamic)null;

//initializes to null; more conventional; can be reassigned a value of any type
object foo = null;

//initializes to null; cannot be reassigned a value of any type
var foo = (T)null;
Run Code Online (Sandbox Code Playgroud)


Sna*_*ake 30

为什么这不可能?

var theNameOfTheVar = (TheType)null;
Run Code Online (Sandbox Code Playgroud)

例如:

var name = (string)null;
Run Code Online (Sandbox Code Playgroud)

就那么简单.

  • 这当然是一个有效的解决方案,但我真的无法想出任何使用它的理由. (2认同)
  • 空无一人.我只是在回答TS问题:) (2认同)

Anj*_*ant 23

这是如何将值初始化var变量的方法

var _myVal = (dynamic)null; 
Run Code Online (Sandbox Code Playgroud)


maf*_*afu 7

A var无法设置,null因为它需要静态输入.

var foo = null;
// compiler goes: "Huh, what's that type of foo?"
Run Code Online (Sandbox Code Playgroud)

但是,您可以使用此构造来解决此问题:

var foo = (string)null;
// compiler goes: "Ah, it's a string. Nice."
Run Code Online (Sandbox Code Playgroud)

我不确定,但从我听到你也可以用dynamic而不是var.这不需要静态类型.

dynamic foo = null;
foo = "hi";
Run Code Online (Sandbox Code Playgroud)

此外,由于我不清楚问题是否var一般意味着关键字或变量:只能将引用(对类)和可空类型设置为null.例如,你可以这样做:

string s = null; // reference
SomeClass c = null; // reference
int? i = null; // nullable
Run Code Online (Sandbox Code Playgroud)

但你不能这样做:

int i = null; // integers cannot contain null
Run Code Online (Sandbox Code Playgroud)


Jas*_*ans 5

没有。var需要初始化为类型,不能为 null。


Has*_*ion 5

好吧,我认为您可以将其分配给一个新对象。就像是:

var v = new object();
Run Code Online (Sandbox Code Playgroud)