为什么在创建对象时,最好使用 var 关键字比真实类型?
Why when creating object it is preferred to use var keyword than real type?
var strList = new List<string>(); //good? List<string> strList = new List<string>(); //why bad?问题不仅仅是列表< T> 。
推荐答案不是 var 一个是坏的。
如果你想让我更具体,我想你应该使用 var 当类型完全明显时,例如:
If you want me to be more specific, I think you should use var only when the type is completely evident, such as:
var employee = new Employee();另一方面,这可能是一个可怕的想法:
On the other side it's probably a horrible idea to do:
var e = GetEmployees();因为很难判断 e 是 Employee 对象或List,数组等。
Because it's hard to tell whether if e is an Employee object, or a List, array, etc.
在不降低可读性的情况下节省您一些工作:
Also is probably right to use it when it saves you some effort while not diminishing readability:
ReallyLongClassName someidentifier = new ReallyLongClassName();VS
var explanatoryIdentifier = new ReallyLongClassName();但最终,这归结于个人喜好,只是 / strong>如果您损害了可读性,请保存一些字符。
But at last, it comes down to be personal preference, just don't ever save you some characters if you are damaging readability.
更多推荐
为什么喜欢var strList = new List< string>(); over list< string&a
发布评论