为什么喜欢var strList = new List< string>(); over list< string> strList = new

编程入门 行业动态 更新时间:2024-10-21 23:23:47
本文介绍了为什么喜欢var strList = new List< string>(); over list< string> strList = new List< string>();?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

为什么在创建对象时,最好使用 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&lt; string&gt;(); over list&lt; string&a

本文发布于:2023-11-07 06:16:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565758.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:喜欢   strList   List   amp   var

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!