没有任何技术原因使用或者类型是已知的不是​​在C#中使用VAR? [英] Is there any technical reason to use or not to use var in C# when the type is known?

查看:149
本文介绍了没有任何技术原因使用或者类型是已知的不是​​在C#中使用VAR?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看来,越来越多的C#代码我读使用 VAR 类型标识符:

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

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

而不是明确声明的类型:

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

甚至当类型是已知的。

我仍在使用中的后者明确的版本,只是因为我觉得有人看完后会更快速地了解哪些类型变量大于如果使用VAR。

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?

推荐答案

有没有技术上的原因。如果类型不能在编译时推断然后代码将无法编译。

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

这篇关于没有任何技术原因使用或者类型是已知的不是​​在C#中使用VAR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆