在開發中到底要不要用var?


var是.net的一個語法糖,在Resharper中推薦都使用這個關鍵字,平常我也是經常用;但是在跟其他程序員推廣使用時,他的一些考慮引發了我的深思,到底該不該使用這個關鍵字呢?

我使用的理由

我使用的理由很簡單

  • 簡化輸入。這個真的很方便,你想想你new一個對象的時候,或者通過一個方法的時候,還得想想這個對象的類型是什么,尤其是像這種復雜的類型:Func<Dictionary<Model.User,List<Model.Roles>>,int> test=new Func<Dictionary<Model.User,List<Model.Roles>>,int>(),用起來得有多辛苦?

  • Resharper強制的時候,你看着Resharper的推薦,總是忍不住的點一下,結果整個VS都是var的類型了

  • 強迫症。如果用各種類型,在new的時候左邊總是對不齊,但是用var就不同了

      var obj1=new List<Model.User>();  
      var obj2=new Dictionary<int,Model.Department>();
    

左邊對的多齊是不?

不使用的理由

同事給我的理由是:用這個關鍵字,你就沒法知道一個這個對象的類型了,尤其在記事本打開的時候,很不爽。只有用vs打開的時候,通過智能感知才知道。

這確實是個問題,我一時也不能反駁。但是隱隱約約我又感覺有點不對。我用這么久了,也沒什么問題是不,也沒有感覺到使用不方便啊。話說了,開發C#的,有幾個又不打開VS的?

讓我們看看老外是怎么看的

在文章To var or not to var – c# implicit variable declaration中提到:

What are the benefits of using var

  • Dont Repeat Yourself (DRY) – Redundant code should be avoided.
  • Faster creation of code
  • Calls for improved naming of variables – can work as a reminder for descriptive naming
  • Improved readability – in some cases (where the repeated type is long and complex)
  • Less code modification if you later need to change the type
  • Clearer distinction of when you really want to specify the type

The disadvantages of using var

  • Loss of readability – in some cases (where the type isn’t obvious)
  • Changes to the type could introduce bugs which the compiler otherwise would have caught for the developer

Conclusion:

In my opinion the var keyword should certainly be used with care, but redundant declarations should be avoided. Therefore it would be preferred to use implicit declarations wherever it’s appropriate, i.e where the type is clear and obvious. Consistency shouldn’t be neglected, but I believe most developers in an organisation would identify the same situations where the type is ambigous.

In the end it’s really about finding a sensible balance. If keeping in mind to use var to avoid repetition and obvious type declarations, the answer is pretty clear of when to var or not… where the type is reasonably obvious.

在文章“WHAT ADVANTAGES DOES USING VAR HAVE OVER THE EXPLICIT TYPE IN C#? [DUPLICATE]”有人是這么認為的:

The point of var is to allow anonymous types, without it they would not be possible and that is the reason it exists. All other uses I consider to be lazy coding.

你是想懶點,還是想累點?

這篇文章總結得也不錯“C# 3.0 Implicit Type Declarations: To var or not to var?

Some cases where it seems just fine to suggest var are:

  1. New object creation expression: var dictionary = new Dictionary<int, string>();
  2. Cast expression: var element = (IElement)obj;
  3. Safe Cast expression: var element = obj as IElement;
  4. Generic method call with explicit type arguments, when return type is generic: var manager = serviceProvider.GetService ()
  5. Generic static method call or property with explicit type arguments, when return type is generic: var manager = Singleton .Instance;

Infoq中有篇文章研究得比較深入:“C# Debate: When Should You Use var?

Overuse of var can make source code less readable for others. It is recommended to use var only when it is necessary, that is, when the variable will be used to store an anonymous type or a collection of anonymous types.

但是,有人提出了另外的意見:
Chris Sutton seems to go further and implies that the type really doesn't matter.

Then the suggestion came up that you should only use var when you don’t know the type. Here is where I differ in opinion and usage. Look at the following snippet

var procs = from p in ServiceController.GetServices()
where p.Status == ServiceControllerStatus.Running
select p;
procs.ToList().ForEach(p=> Console.WriteLine(p.ServiceName));

procs is certainly IEnumerable but it doesn’t matter to me. I primarily care that procs is a list and that the individual items in the list have a Property called ServiceName. The underlying type is important to the compiler, but the people that have to read code aren’t compilers right?

總結

使用var可以:

  • 減少編程語言中的重復工作(DRY)
  • 減少編程中的噪聲干擾
  • 減少編碼
  • 在某些情況下,會提升可閱讀性

因此在以下情況,建議使用var

  • 當你能夠通過一個聲明明確的看到類型時。如:var dic=new Dictionary<int,List<string>>();var element = (IElement)objvar element = obj as IElement
  • 使用泛型時:var manager = serviceProvider.GetService<IManager>()var manager = Singleton<Manager>.Instance
  • 當你使用匿名類時:var person = new { Name = "Peter", Age=4};

其他情況下建議還是書寫完全的類型名稱,因為過度使用var,會減低整體代碼的可讀性,尤其在沒有IDE的智能提示的情況下,用var可能會導致閱讀代碼的人的困惑。

如何在Resharper中關閉這個提示

在Resharper中關閉var的強制提示


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM