C# 使用隐式类型的局部变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/650919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using implicitly typed local variables
提问by M4N
I just installed a trial version of ReSharperand one of the first things I noticed is that it always suggests to replace explicitly typed local variables with implicitly typed ones, e.g:
我刚刚安装了ReSharper的试用版,我注意到的第一件事是它总是建议用隐式类型的变量替换显式类型的局部变量,例如:
public string SomeMethod(int aParam)
{
int aNumber = SomeOtherMethod(aParam);
// should be changed to:
var aNumber = SomeOtherMethod(aParam);
}
I think explicitly typed variables are more readable (more explicit).
我认为显式类型的变量更具可读性(更明确)。
What do you think about ReSharper's suggestion? Is there any advantage in using implicitly typed variables? When do you use implicit/explict vars?
您如何看待 ReSharper 的建议?使用隐式类型变量有什么好处吗?你什么时候使用隐式/显式变量?
采纳答案by Rene
I personally only use “var” when I can clearly distinguish the variable Type by just reading the declaration, for example:
我个人只在通过阅读声明就可以清楚地区分变量类型时才使用“var”,例如:
var someVariable = new List<int>();
In the example above, its evident that “var” refers to “List<int>”.
在上面的例子中,很明显“var”指的是“List<int>”。
I don't like to use “var” when I have to go to some method definition to find out what variable type “var” represents or by having to rely on visual studio intelli-popup or whatever that is called, for example this in not ok to me:
当我必须去某些方法定义以找出变量类型“var”代表什么或不得不依赖visual studio intelli-popup或任何被调用的东西时,我不喜欢使用“var”,例如this in对我不好:
var someVaraible = SomeMethod();
I mean, what is the “SomeMethod” function supposed to return? Can you tell just by looking at the line of code? No you can't, so that is why I avoid using “var” on those situations.
我的意思是,“SomeMethod”函数应该返回什么?你能通过查看代码行来判断吗?不,你不能,所以这就是为什么我避免在这些情况下使用“var”。
回答by Daniel Henry
It's just easier to type the var pseudo-keyword at times than a huge type name, especially if a generic could be involved. However, you should know they're functionally identical. There's no performance difference or anything either way. The compiler derives the type of the right-side of the assignment and replaces var with that type. It's not happening at run-time like a VB variant.
有时输入 var 伪关键字比输入巨大的类型名称更容易,尤其是在可能涉及泛型的情况下。但是,您应该知道它们在功能上是相同的。没有性能差异或任何方式。编译器导出赋值右侧的类型,并用该类型替换 var。它不像 VB 变体那样在运行时发生。
回答by Razzie
There's a lot of discussion about this, but I think it all comes down to personal taste, just like using the 'this' keyword almost everywhere.
关于这个有很多讨论,但我认为这一切都归结为个人品味,就像几乎在任何地方都使用“this”关键字一样。
I personallyprefer explictly typed variables, but when using nested generic collections things can become more readable using an implicitly typed variable. Look at:
我个人更喜欢显式类型的变量,但是当使用嵌套泛型集合时,使用隐式类型的变量可以变得更具可读性。看着:
Dictionary<string, Dictionary<string, string>> myDictionary = new Dictionary<string, Dictionary<string, string>>();
vs:
对比:
var myDictionary = new Dictionary<string, Dictionary<string, string>>();
EDIT: this SO topic covers the same topic, with some nice replies: What to use: var or object name type?
编辑:这个 SO 主题涵盖了相同的主题,有一些不错的回复:What to use: var or object name type?
EDIT2: Working a lot with async nowadays, I find that using explicity typed variables can sometimes prevent nasty bugs. Consider this silly example where you would want to return the Id of a user. Also consider that GetUserAsync
returns a Task<User>
. If you use implicitly typed variables, you would end up using something like this:
EDIT2:现在使用 async 做了很多工作,我发现使用显式类型的变量有时可以防止讨厌的错误。考虑这个愚蠢的示例,您希望返回用户的 ID。还要考虑GetUserAsync
返回 a Task<User>
。如果你使用隐式类型变量,你最终会使用这样的东西:
public long GetUserId()
{
var user = GetUserAsync();
return user.Id;
}
This compiles, but it is wrong. 'user' is actually a Task<User>
. And it compiles as Task
also has an Id
property. In this case, one would accidentally return the Id of a Task instead of the User.
这编译,但它是错误的。“用户”实际上是一个Task<User>
. 它编译为Task
也有一个Id
属性。在这种情况下,人们会不小心返回任务的 Id 而不是用户。
public long GetUserId()
{
User user = GetUserAsync();
return user.Id;
}
The above does not compile, as the compiler will complain that you cannot cast a Task to a User. Adding the await
keyword of course solves this.
上面没有编译,因为编译器会抱怨你不能将任务转换为用户。添加await
关键字当然可以解决这个问题。
I've actually had this happen to me once :-)
实际上,我曾经遇到过这种情况:-)
回答by Dustin Campbell
FWIW, the var keyword is plainly readable in many cases. Especially if...
FWIW, var 关键字在许多情况下是显而易见的。特别是如果...
The right-side of the assignment is a constructor expression.
var map = new Dictionary>();
Local variables have good names.
赋值的右侧是构造函数表达式。
var map = 新字典>();
局部变量有好名字。
HTH
HTH
回答by uli78
Just in case some haven't noticed yet, you can easily change the “suggestions” in Reshaper (Reshaper -> Options -> Languages -> Context Actions -> “Replace explicit type specification with ‘var'”).
以防万一有些人还没有注意到,您可以轻松地更改 Reshaper 中的“建议”(Reshaper -> Options -> Languages -> Context Actions -> “Replace explicit type specification with 'var'”)。
I personally prefer to have explicit type specifications everywhere, but I'm not too fussy about it.
我个人更喜欢在任何地方都有明确的类型规范,但我对此并不太挑剔。