问题
Possible Duplicates:
What to use: var or object name type?
Use of var keyword in C#
What’s the point of the var keyword?
Should I always favour implictly typed local variables in C# 3.0?
I have just installed a trial version of ReSharper to evaluate it for my company. One thing that I have noticed is it is suggesting that I change the following (made up example):
string s = "";
to
var s = "";
Is it best practice to use the var keyword rather than using the Object Type when declaring variables? What advantages does it give. For context I am a former Java developer who has just transitioned to the .Net works.
回答1:
I think it's fine to use var
where it makes the code easier to read, which for me would mean that the type that var
is replacing must be completely obvious.
For example, this would be a good use of var
(contrived example):
var thing = new Dictionary<int, KeyValuePair<string, int>>();
However this would be a bad use of var
:
var thing = GetThingFromDatabase();
回答2:
I find it helpful in some cases where the type declaration is very long, for example:
Dictionary<int, string> item = new Dictionary<int, string>();
becomes
var item = new Dictionary<int, string>();
回答3:
It amounts to the same thing because using the var keyword, the variable is implicity typed and the compiler infers the type at build time. I prefer to specify the type rather than use var in most cases, so I change my resharper settings.
回答4:
As i remember it Resharper just says that it could be written this way. It doesn't say that you should.
Alot of suggestions is just suggestions which I turned of the first time i saw them.. That being one of them.
Another was that it said was that it is redundant to write "this.someProperty", while i think the code gets easier to read by doing that.
回答5:
Resharper also has suggestion to transform if statement to true or not true. Almost the same thing, but it depends on your style of coding. So, when you find using var more comfortable - use this suggestion.
来源:https://stackoverflow.com/questions/1205329/c-sharp-var-keyword-usage