我什么时候应该使用“var”而不是“对象”?

发布于 2024-11-14 06:17:16 字数 191 浏览 1 评论 0原文

我想知道什么时候应该使用 var

C# 中的几乎所有内容(可能除了原语和一些更奇怪的情况)都派生自 Object。

那么使用实际类型不是更好的做法吗?或者至少object

(我已经编程了一段时间了,我严格的观点是 var 是邪恶的)

I was wondering when should you use var?

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 ?

(I've been programming for a while, and my strict point of view is that var is evil)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

清秋悲枫 2024-11-21 06:17:16

您误解了:var 不是一种类型。 var 指示编译器根据变量的初始化使用正确的变量类型。

示例:

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 时,您的变量仍然是强类型的。

因此,var 并不是“邪恶的”。相反,它非常方便,正如我在其他地方,我广泛使用它。 Eric Lippert 是 C# 背后的主要人物之一,他还撰写了 详细关于 var 是否是不好的做法。简而言之,“不”。

You misunderstand: var isn’t a type. var instructs the compiler to use the correct type for a variable, based on its initialisation.

Example:

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

Your variables are still strongly typed when using 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”.

甜心小果奶 2024-11-21 06:17:16

我认为您将 vardynamic 混为一谈。使用 var 与您写出整个类型名称完全相同*,并且编译器将它们呈现为相同的代码。 Eric Lippert 的博客提供了一些关于 var 关键字的作用以及何时使用它的精彩信息。

来自 Eric Lippert 的文章 隐式类型的使用和误用:

总结一下,我的建议是:

  • 必要时使用 var;当您使用匿名类型时。
  • 当声明的类型从声明中显而易见时使用 var
    初始化器,特别是如果它是一个
    对象创建。这消除了
    冗余。
  • 如果代码强调语义“业务”,请考虑使用 var
    变量的目的”并淡化
    其“机械”细节
    存储。
  • 如果需要使代码正确,请使用显式类型
    理解并维护。
  • 无论是否使用“var”,都使用描述性变量名称。
    变量名应该代表
    变量的语义,而不是细节
    其存储; “decimalRate”不好;
    “利率”很好。

*有些人可能会对我的“完全相同”的说法提出异议。对于匿名类型来说,严格来说并非如此,但那是因为您无法合法地写出类型名称。

You're conflating var with dynamic, I think. Using var is exactly the same* as if you had written out the entire type name, and the compiler renders them into the same code. Eric Lippert's blog offers some excellent information on what the var keyword does and when to use it.

From Eric Lippert's article Uses and misuses of implicit typing:

Summing up, my advice is:

  • Use var when you have to; when you are using anonymous types.
  • Use var when the type of the declaration is obvious from the
    initializer, especially if it is an
    object creation. This eliminates
    redundancy.
  • Consider using var if the code emphasizes the semantic "business
    purpose" of the variable and downplays
    the "mechanical" details of its
    storage.
  • Use explicit types if doing so is necessary for the code to be correctly
    understood and maintained.
  • Use descriptive variable names regardless of whether you use "var".
    Variable names should represent the
    semantics of the variable, not details
    of its storage; "decimalRate" is bad;
    "interestRate" is good.

*Some might take issue with my "exactly the same" statement. It isn't strictly true for anonymous types, but that's because you can't legally write out the type name.

救星 2024-11-21 06:17:16

使用 object 你会丢失所有静态类型信息(当用于值类型时,它甚至会导致装箱)。因此,使用 object 与使用 var 非常不同。

另一方面,var 相当于使用实际(静态)类型。因此,当声明实际类型不可能或不方便时,您可以使用它。

  • 需要 var 的一种情况是使用匿名类型时。它们没有名称(挑剔:只是编译器生成的您不知道的名称),因此您无法显式命名类型。

  • 使用 var 很方便的一种情况是当您的类型名很长时。使用嵌套泛型时有时会发生这种情况。

  • foreach 循环中,您可以避免不安全的隐式转换。

    并且

Using object you'd lose all static type information (and when used on a value type it even causes boxing). So using object is very different from using var.

var on the other hand is equivalent to using the actual(static) type. So you use it when stating the actual type is either impossible or inconvenient.

  • One scenario where var is necessary is when using anonymous types. They have no name(nitpick: only a compiler generated name that you don't know), so you can't name the type explicitly.

  • One case where using var is convenient is when you're typename is very long. This happens sometimes when using nested generics.

  • And in foreach loops you avoid the unsafe implicit cast.

爱,才寂寞 2024-11-21 06:17:16

varobject 是两个完全不同的东西。

使用var,编译器会为您推断类型。 object 就是一个对象,由于 C# 是一种强类型语言,因此您会丢失有关该实例的所有信息。

请参阅 C# 规范第 26.1 节:

在隐式类型局部变量声明中,声明的局部变量的类型是从
用于初始化变量的表达式。当局部变量声明指定 var 作为类型并且 no
名为 var 的类型在作用域内,该声明是隐式类型局部变量声明。

var and object are two entirely different things.

With var, the compiler is inferring the type for you. An object is an object, and you lose any information you had about the instance since C# is a strongly typed language.

See section 26.1 from the C# specification:

In an implicitly typed local variable declaration, the type of the local variable being declared is inferred from
the expression used to initialize the variable. When a local variable declaration specifies var as the type and no
type named var is in scope, the declaration is an implicitly typed local variable declaration.

鲜血染红嫁衣 2024-11-21 06:17:16

您的“严格观点”有点误导... var 确实使用实际类型。编译器分析右侧表达式的返回类型,并将其用作赋值的类型。

Your "strict point of view" is a little misinformed... var DOES use the actual type. The compiler analyzes the return type of the expression on the right hand side and uses that as the type of the assignment.

一世旳自豪 2024-11-21 06:17:16

var 不是类型。 var 对编译器说“我不确定/不愿意在此处输入正确的类型名称,请根据此语句的上下文为我推断类型”。

Object 将对象转换为 Object 类型。因此,您会丢失任何类型信息,因此无法再调用在层次结构中低于 Object 的级别定义的特定方法、访问属性等。

var is not a type. var says to the compiler 'I'm not sure/can't be bothered typing the proper type name here, please infer the type for me based on the context of this statement'.

Object casts the object to type Object. As a result you lose any type information, so can no longer call specific methods, access properties etc that are defined at a level lower in the hierarchy than Object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文