当类型已知时,是否有任何技术原因在 C# 中使用或不使用 var?

发布于 2024-08-15 01:56:21 字数 390 浏览 6 评论 0原文

似乎我读到的越来越多的 C# 代码使用 var 类型标识符:

foreach (var itemChange in ItemChanges)
{
   //... 
}

而不是显式声明类型:

foreach (ItemChange itemChange in ItemChanges)
{
   //... 
}

即使类型已知。

我仍然使用后者显式版本,只是因为我认为稍后阅读它的人会比使用 var 更快地理解变量的类型。

但是有什么技术理由需要使用其中之一吗?

It seems that more and more C# code I read uses the var type identifier:

foreach (var itemChange in ItemChanges)
{
   //... 
}

instead of explicitly stating the type:

foreach (ItemChange itemChange in ItemChanges)
{
   //... 
}

even when the type is known.

I am still using the latter explicit version just because I think someone reading it later will more quickly understand which type a variable is than if you use var.

But is there any technical reason to use one or the other?

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

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

发布评论

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

评论(8

舞袖。长 2024-08-22 01:56:21

没有技术原因。如果在编译时无法推断类型,则代码将无法编译。

您说得对,在某些情况下,为了可读性,使用显式类型可能会更好,例如,

var obj = SomeMethod(); // what's the type? you'd have to inspect SomeMethod()
SomeClass obj = SomeMethod(); // the type is obvious

但在其他情况下,使用 var 非常有意义,例如

var obj = new SomeClass(); // the type is obvious
SomeClass obj = new SomeClass(); // the duplication of type is unnecessary

There is no technical reason. If the type cannot be inferred at compile time then the code will not compile.

You are right in stating there are instances where it may be better to use an explicit type for readabilty, e.g.

var obj = SomeMethod(); // what's the type? you'd have to inspect SomeMethod()
SomeClass obj = SomeMethod(); // the type is obvious

but other instances where using var makes perfect sense, e.g.

var obj = new SomeClass(); // the type is obvious
SomeClass obj = new SomeClass(); // the duplication of type is unnecessary
烂人 2024-08-22 01:56:21

不,只是可读性。

No, just readability.

梦里°也失望 2024-08-22 01:56:21

一般来说没有技术原因。可读性——无论从哪个方向——都是唯一真正的因素。

然而,一个小警告是 var 将推断变量的 static 类型。如果您想要子类或超类类型,您需要自己进行转换。对于 foreach 的情况,如您的示例所示,通常只需使用子类类型声明循环变量即可“免费”执行向下转换。

经典示例是迭代 XML NodeList,您知道XmlElement 列表,但 Nodelist 被键入为 集合XmlNode。当然,您可以使用强制转换或 as 来获取您想要的类型,但这似乎违背了使用类型推断的目的:-)

当然,编译器会让您知道当您尝试使用仅可用于 XmlElement 的节点成员时,就会出现这种情况 - 因此严格来说它仍然不是技术差异。


另一件有点烦人的事情是,如果您使用像 Resharper 这样的工具,它会非常积极地建议您在每种可能的情况下使用 var。例如,当它建议您将 int 声明更改为 var 时,这尤其令人烦恼!

但是,除非您关闭该功能,否则您使用 var 的次数越多,从 Resharper 获得的“噪音”就会越少。

In general no technical reason. Readability - in either direction - is the only real factor.

However, one small caveat is that var will infer the static type of the variable. If you want a sub or super class type you'll need to do the casting yourself. In the case of a foreach, as in your example, you can usually get downcasting performed for you "for free" just by declaring your loop variable with the subclass type.

The classic example is iterating over an XML NodeList that you know is a list of XmlElement, but Nodelist is typed as a collection of XmlNodes. Of course you can use a cast or an as to get back the type you want, but that would seem to defeat the purpose of using type inference :-)

Of course, the compiler will let you know about this as soon as you try to use a member of the node that is only available to XmlElement - so it's still not strictly a technical difference.


Another thing that is a little annoying is that if you use a tool like Resharper, it's very aggressive about suggesting you use var in every possible situation. It's particularly annoying when it recommends you change, for example, an int declaration into a var!

However, unless you turn that feature off, you'll get less "noise" from Resharper the more you use var.

画骨成沙 2024-08-22 01:56:21

我所知道的唯一技术原因是您可以在没有 var 的情况下执行隐式转换,例如,

int i = 5;
double a = i; // implicit cast with explicit types

但在这里我更喜欢 var 因为它使转换显式;虽然我不太关心在执行表示更改类型转换时所关心的类型:

var a = (double)i; // explicit cast with implicit types

但正如您所说,真正的一般原因是可读性。您需要问自己的问题是,为什么您认为确切的具体类型对于可读性很重要?您是否总是编写 Linq 查询来调用具体类型,例如

from ItemChange itemChange in ItemChanges

// instead of

from itemChange in ItemChanges

同样,您是否总是调用泛型方法的类型参数而不是使用类型推断,例如

ItemChanges.Select<ItemChange, ItemChange>((ItemChange itemChange) => ...);

// instead of

ItemChanges.Select(itemChange => ...);

或者您是否乐意让编译器为您做一些工作并让它工作以没有明确说明类型信息为“代价”来输出类型?

如果您对 linq 和泛型方法中的类型推断感到满意,那么您已经做出决定,您可以接受不在任何地方显式拼写类型,并且您可能没有发现代码的可读性有任何下降结果(事实上,您可能发现恰恰相反)。因此,使用 var 只是在您已经走上的同一道路上又迈出了一步。

The only technical reason I know of is that you can perform implicit casts without var, e.g.

int i = 5;
double a = i; // implicit cast with explicit types

but here I much prefer var as it makes the cast explicit; while I don't care so much about the types I do care when I'm performing a representation changing type conversion:

var a = (double)i; // explicit cast with implicit types

But really the general reason is readability, as you said. The question you need to ask yourself is why you think the exact concrete type is important for readability? Do you always write Linq queries calling out the concrete type, e.g.

from ItemChange itemChange in ItemChanges

// instead of

from itemChange in ItemChanges

Similarly, do you always call out the type arguments to generic methods instead of using type inference, e.g.

ItemChanges.Select<ItemChange, ItemChange>((ItemChange itemChange) => ...);

// instead of

ItemChanges.Select(itemChange => ...);

Or are you happy to let the compiler do some work for you and let it work out the types, at the 'expense' of not having the type information explicitly stated?

If you're happy with type inference in linq and generic methods, then you've already made the decision that you're OK with not having types explicitly spelled out everywhere, and you probably haven't found your code to be any less readable as a result (in fact, you've probably found quite the opposite). So using var is just another step down the same path that you're already on.

匿名的好友 2024-08-22 01:56:21

var 是 C# 3.0 功能,仅在匿名类型中强制使用

因为以下代码

var v = new { Amount = 108, Message = "Hello" };

动态创建新的匿名类型,所以 var 使用是强制的。例如,var 在通常动态创建类型的 Linq 中特别有用。

在任何其他情况下,这只是最终应用程序的品味问题(在编译期间解决)。但对于代码阅读器来说,我认为“var”的信息量不如类型本身。

var is a C# 3.0 feature only mandatory in anonymous type

Because following code

var v = new { Amount = 108, Message = "Hello" };

dynamically create a new anonymous type, var usage is mandatory. For example, var is particularly useful in Linq where type are often created dynamically.

In any other situations, it's only a matter of taste for final application (it's resolved during compilation). But for code readers, I think 'var' is less informative that type itself.

黑白记忆 2024-08-22 01:56:21

不可以。使用 var 可以提高可读性,反之亦然。

No. Use var where it improves readability and vice versa.

潇烟暮雨 2024-08-22 01:56:21

var 是 C# 3.x+ 的功能,不是吗?如果不使用它,您的代码也与其他版本更兼容。

当您搜索“var C#”时,SO 中有很多有趣的问题

var is a C# 3.x+ feature, isn't it? without using that, your code is more compatible with other versions too.

And there is lots of interesting questions in SO, when you search "var C#"

完美的未来在梦里 2024-08-22 01:56:21

在程序的任何给定状态下,除了匿名类型之外,没有任何技术原因需要使用 var。

但是,使用 var 允许程序更改而无需编辑它。那么

public int SomeMethod(){}
public List<T> SomeOtherMethod<T>(T parameter);

var x = SomeMethod();
var y = SomeOtherMethod(x);

可以工作(并且 y 将是 List)。如果您使用

int x = SomeMethod();
List<int> y = SomeOtherMethod(x);

then if SomeMethod() 更改为返回 long,那么您必须更改 y 的定义。

我见过这种事情在整个程序中传播,需要数百次更改。特殊情况是更改数据访问代码以返回 ReadOnlyCollection 而不是 List。需要更改的代码太多,因此我将所有显式提及的 List 更改为 var,并且代码永远不需要再次更改。

There is no technical reason to use var, other than anonymous types, in any given state of the program.

However, using var allows the program to change without you needing to edit it. Given

public int SomeMethod(){}
public List<T> SomeOtherMethod<T>(T parameter);

then

var x = SomeMethod();
var y = SomeOtherMethod(x);

Will work (and y will be List<int>). If you had used

int x = SomeMethod();
List<int> y = SomeOtherMethod(x);

then if SomeMethod() were changed to return long, then you'd have to change the definition of y.

I've seen this kind of thing propagate throughout a program, requiring hundreds of changes. The particular case was changing data access code to return ReadOnlyCollection<T> rather than List<T>. There were so many code changes required, that I changed all explicit mentions of List<T> to var, and the code will never need to change again.

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