C#中的Var关键字以及为什么Resharper建议使用var [英] Var Keyword in C# and why Resharper Suggest to Use var

查看:272
本文介绍了C#中的Var关键字以及为什么Resharper建议使用var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是C#中的var关键字以及为什么Resharper一直建议使用var?

What is var Keyword in C# and Why Resharper keep suggesting to use var ?

推荐答案

如何阅读文档 [ ^ ]?


我无法告诉你为什么ReSharper会赞扬var类型的强类型(有无穷无尽的辩论)使用哪一个,似乎ReSharper支持var),但我可以告诉你,编译后没有差异(CLR中没有var,它是编译器功能)。如果编译器无法找出类型(或为i创建匿名类型),则会抛出错误。



引入了var'type'来处理你编写的代码创建一个新的但是匿名的类型的情况,你太懒了(IMO)为它声明一个类型并使用它...



请参阅此处

http://msdn.microsoft.com/en- us / library / vstudio / bb383973.aspx [ ^ ]
I can't tell you why ReSharper praise var over strongly typed version (there is an endless debate over which one to use, and it seem that ReSharper took side in favor of var), but I can tell you that there are no difference after compilation (no var in CLR, it's a compiler feature). If the compiler can't figure out the type (or create an anonymous type for i) it will throw an error.

The var 'type' was introduced to handle cases where the code you wrote creates a new, but anonymous type, and you are too lazy (IMO) to declare a type for it and use it...

See here
http://msdn.microsoft.com/en-us/library/vstudio/bb383973.aspx[^]


与几乎所有ReSharper的自动类型/智能感知设施一样,最终用户可以修改'var的处理方式,从六个选项中选择(! )包括只是让R#建议使用它,从不建议使用它,或自动使用它(默认):



你可以通过ReSharper |来禁用这个建议。选项|代码检查|检查严重程度:[ ^ ]。



给我使用'var使感觉类型定义...没有'var ...会出现在赋值运算符的左右两侧。



如果我要去write:
Like almost all of ReSharper's auto-type/intellisense facilities, the end-user can modify how 'var is handled, choosing from six options (!) including just having R# suggest using it, never suggest it, or automatically using it (the default):

"You can disable this suggestion through "ReSharper | Options | Code Inspection | Inspection Severity:" [^].

To me using 'var makes the most sense where the Type definition ... without 'var ... would appear on both left and right hand sides of the assignment operator.

If I were going to write:
Dictionary<dictionary><string,>, List<int>> dctDctList = new Dictionary<dictionary><string,>, List<int>>();</int></dictionary></int></dictionary>

然后,我很感激能够写:

Then, I do appreciate being able to write:

var dctDctList = new Dictionary<dictionary><string,>, List<int>>();</int></dictionary>

但是,'var的另一个主要用途是作为运行的占位符 -time编译器生成的复杂类型,同样有效。

But, the other major use of 'var, as a "placeholder" for a run-time compiler-generated complex Type, is just as valid.


这篇关于C#中的Var关键字以及为什么Resharper建议使用var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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