什么时候应该使用" VAR"而不是"反对"? [英] When should I use "var" instead of "object"?
问题描述
当你应该使用我想知道 VAR
?
I was wondering when should you use var
?
几乎所有的东西在C#中,除了可能的原语和一些更奇怪的情况下,派生自Object。
Almost anything in C#, except for maybe the primitives and a few more odd cases, derive from Object.
所以,岂不是更好的做法是使用实际的类型?或者至少对象
?
So wouldn't it be a better practice to use that actual types ? or at least object
?
(我已经编写了一段时间,我的严格的观点是该 VAR
是邪恶的)
(I've been programming for a while, and my strict point of view is that var
is evil)
推荐答案
您误解: VAR
不是一个类型。 VAR
指示编译器使用的正确的类型变量,是根据它的初始化。
You misunderstand: var
isn’t a type. var
instructs the compiler to use the correct type for a variable, based on its initialisation.
例如:
var s = "hello"; // s is of type string
var i = 42; // i is of type int
var x = new [] { 43.3 }; // x is of type double[]
var y = new Foo(); // y is of type Foo
您使用的变量时仍强类型 VAR
。
Your variables are still strongly typed when using var
.
因此, VAR
不是邪恶。相反,这是非常方便的,正如我已经说过别处一>,我用它广泛。埃里克利珀,背后C#的主要人之一,还写的很详细的了解是否 VAR
是不好的做法。概括地说,没有。
As a consequence, var
isn’t "evil". On the contrary, it’s very handy and as I’ve said elsewhere, I use it extensively. Eric Lippert, one of the main people behind C#, has also written in great detail about whether var
is bad practice. In a nutshell, "no".
这篇关于什么时候应该使用" VAR"而不是"反对"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!