主頁 >  其他 > [譯文] 為什么你在 C# 里總是應該使用 "var" 關鍵字

[譯文] 為什么你在 C# 里總是應該使用 "var" 關鍵字

2020-09-11 18:41:29 其他

Using the ‘var’ keyword in C# has always spurred a hot debate among developers. I believe ‘var’ should be used at all times. I believe this not because I choose to be “lazy,” as those who argue against it frequently claim. Of all the reasons I use ‘var’, laziness is not one of them.

在 C# 中使用 var 關鍵字一直引起開發人員的激烈爭論, 我認為應始終使用 var. 我相信這不是因為我選擇變得 懶惰, 正如經常聲稱反對它的人的那樣, 在我使用 var 的所有原因中, 懶惰不是其中之一.

I’ve argued for the constant use of ‘var’ countless times; this blog post is a collection of thoughts that I have compiled resulting from my arguments. Below are my reasons for using ‘var’ all of the time.

我主張無時無刻地使用 var, 這篇博客文章是我根據自己的論點整理出的想法的集合, 以下是我一直使用 var 的原因.

原文

It decreases code-coupling (減少代碼耦合)

Coupling between code and its dependent code can be reduced by using ‘var’. I do not mean coupling from an architectural perspective nor at an IL-level (the type is inferred anyway), but simply at the code level.

使用 var 可以減少代碼與其從屬代碼之間的耦合, 我的意思是, 不是從體系結構的角度耦合, 也不是在IL級別(無論如何推斷型別), 而是在代碼級別.

Example (示例)

Imagine there are 20 explicit type references spanning over twenty code files to an object that returned an another object of type IFoo. By explicit type references, I mean by prefacing each variable name with IFoo. What happens if IFoo changes to IBar, but the interface’s methods are kept the same?

假設有 20 個顯式型別參考, 跨越 20 多個代碼檔案, 回傳一個型別為 IFoo 的物件. 通過顯式型別參考, 我的意思是在每個變數名前面加上 IFoo, 如果將 IFoo 更改為 IBar, 介面的方法保持不變, 會發生什么?

Wouldn’t you have to change it in 20 distinct places? Doesn’t this increase coupling? If ‘var’ was used, would you have to change anything? Now, one could argue that it is trivial to change IFoo to IBar in a tool like ReSharper and have all of the references changed automatically. However, what if IFoo is outside of our control? It could live outside the solution or it could be a third-party library.

是否需要在 20 個不同的地方就行修改? 這不就是增加了耦合? 若使用 var, 需要修改什么嗎? 現在, 有人可能會爭辯道, 在 ReSharper 之類的工具中將 IFoo 修改為 IBar 并不重要, 且可以自動更正所有參考. 但是, 倘若 IFoo 超出我們的控制范圍了? 它可以存在與解決方案之外, 也可以是第三方庫.

It is completely redundant with any expression involving the "new" operator (它對于任何涉及 "new" 運算子的運算式都是完全多余的)

Especially with generics:

尤其是在泛型:

ICalculator<GBPCurrency, GBPTaxType> calculator = new GBPCalculator<GBPCurrency, GBPTaxType>();

can be shorted to:

可以縮寫為:

var calculator = new GBPCalculator<GBPCurrency, GBPTaxType>();

Even if calculator is returned from a method (such as when implementing the repository pattern), if the method name is expressive enough it is obvious the object is a calculator. The name of the variable should be expressive enough for you to know what the object it represents is. This is important to realize: the variable expresses not what type it represents, but what the instance of that type actually is. An instance of a type is truly an object, and should be treated as such.

即使計算器是從方法回傳的 (例如, 在實作倉儲模式時), 如果方法名具有足夠的表達力, 則物件顯然是個計算器. 變數的名稱應該具有足夠的表達力, 讓人知道它所表達的物件是什么. 認識到這點十分重要: 變數表示的不是它所表示的型別, 而是該型別的實體實際上是什么. 一個型別的實體確實是一個物件, 應該這樣對待.

There is a distinction between an object and its type: an object exists at runtime, it has properties and behaviors; types simply describe what an object should be. Knowing what type an object should be simply adds more noise to the source code, distracting the coder from what an object really is.

物件和它的型別之間有個區別: 物件的屬性和行為存在于運行時, 型別只是簡單地表述了物件應該是什么, 知道物件應該是什么型別, 只會給源代碼帶來更多的干擾, 從而是開發者分心, 無法真正了解物件是什么.

An object may be brought into this world by following the rules governed by a type, but this is only secondary information. What the object actually is and how it behaves is more important than its type. When we use an object at runtime, we are dependent on its methods and properties, not its type. These methods and properties are an object’s behaviors, and it is behaviors we are dependent upon.

物件可以通過遵循由型別控制的規則而引入, 但這僅僅是輔助資訊, 物件實際是什么以及其行為比其型別更重要. 當我們在運行時使用一個物件時, 依賴于它的方法和屬性, 而不是它的型別. 這些方法和屬性是物件的行為, 也是我們所依賴的行為.

The argument for knowing a variable's type has been brought up in the past. The move from Hungarian notation in Microsoft-based C++ to non-Hungarian notation found in C# is a great example of this once hot topic. Most Microsoft-based C++ developers at the time felt putting type identifiers in front of variable names was helpful, yet Microsoft published coding standards for C# that conflicted with these feelings.

過去曾提出了解變數型別的爭議, 從基于微軟的 C++ 中的匈牙利命名法到 C# 中的非匈牙利命名法的轉變, 就是這個曾經熱門話題的一個很好的例子. 當時, 大多數基于微軟的 C++ 開發者都認為將型別識別符號放在變數之前是有幫助的, 然而, 這與微軟發布的 C# 編碼標準與之相沖突.

It was a major culture change and mind-shift to get developers to accept non-Hungarian notation. I was among those who thought that non-Hungarian variable naming was downright wicked heresy and anyone following such a practice must be lazy and did not care about their profession. If knowing a variable’s type is so important, shouldn’t we then preface variable names in Hungarian style to know more information about an object's type?

讓開發者接受非匈牙利命名法是個重大的文化變革和思想轉變. 我曾經就認為, 任何遵循非匈牙利變數命名法的人一定是懶惰的, 不管他是什么職業, 是徹頭徹尾邪惡的異端邪教. 如果知道變數的型別是非常重要的, 那么我們難道不應該以匈牙利命名法的風格前綴變數名以了解有關物件的型別的更多資訊嗎?

You shouldn't have to care what the type of an object is (不必關心物件的型別)

You should only care what you are trying do with an object, not what type an object may come from. The methods you are attempting to call on an object are its object contract, not the type. If variable names, methods, and properties are named appropriately, then the type is simply redundant.

應該專注于利用物件做什么, 而非關注物件來自何種型別. 嘗試呼叫物件的方法是物件契約, 而非型別. 若對變數名, 方法和屬性作了恰當的命名, 那么型別則是冗余.

In the previous example, the word "calculator" was repeated three times. In that example, you only need to know that the instance of a type (the object) is a calculator, and it allows you to call a particular method or property.

如前例所示, 單詞 calculator 重復了三次, 示例中, 只需要知道型別 (物件) 的實體是一個 calculator (計算器), 并且它允許呼叫特定的方法或者屬性.

The only reason a calculator object was created was so that other code could interact with its object contract. Other code needs the calculator’s methods and properties to get something done. This need has no dependency on any type, only on an object’s behaviors..

創建 calculator (計算器)物件的惟一原因是, 其他代碼可以與其物件契約進行互動. 其他代碼需要計算器的方法和屬性來完成一些作業. 這種需求不依賴于任何型別, 只依賴于物件的行為.

For example, as long as the object is a calculator, and the dependent code needs to call a method named ,” then the dependent code is coupled to an object with a method called “CalculateTax” and not a specific type. This allows for much more flexibility, because now the variable can reference any type as long as that type supports the “CalculateTax” method.

比如, 依賴代碼需要呼叫一個名為 "CalculateTax" 的方法, 物件只要是個 calculator (計算器), 那么依賴代碼就會與一個名為 CalculateTax 的方法 (而不是特定型別) 耦合到一個物件上, 這允許更大的靈活性, 因為現在變數可以參考任何型別, 只要該型別支持 CalculateTax 方法.

‘var’ is less noisy than explicitly referencing the type (與顯式參考型別相比, “var”的噪聲更小)

As programming languages evolve, we spend less time telling the compiler and the computer what to do and more time expressing problems that exist in the specific domain we are working in.

隨著編程語言的發展, 我們花更少的時間告訴編譯器和計算機該做什么, 而是花更多的時間來表達我們作業的存在于特定領域的問題.

For example, there are a number of things in C++ that are very technical with respect to the machine, but have nothing to do with the domain. If you are a customer of Quicken or Microsoft Money, all you really want to do is manage your finances better. These software packages allow you to do that.

比如, 在 C++ 中, 有許多與計算機相關的技術問題, 卻與特定領域無關. 如果你是 Quicken (一款家庭及個人財務管理軟體) 或 Microsoft Money 的用戶, 你真正想做的只是更好地管理你的財務. 這些軟體也正是讓你這樣做的.

The better a software package can do this for you, the more valuable it is to you. Therefore, from a development perspective value is defined by how well a software package solves a user's problem. When we set out to develop such software, the only code that is valuable is the code that contributes to solving a particular user’s problem. The rest of the code is unfortunately a necessary waste, but is required due to limitations of technology.

一個軟體為你做得越好, 它對你就越有價值. 因此, 從開發的角度來看, 價值是由軟體解決用戶問題的能力來定義的. 當我們開始開發這樣的軟體時, 唯一有價值的代碼是幫助解決特定用戶問題的代碼. 遺憾的是, 剩下的代碼是必要的浪費, 這是由于技術限制而必需的.

If we had infinite memory, we would not need to worry about deleting pointers in C++ or garbage collection in C#. However, memory is a limitation and therefore the technician in us has to find ways of coping with this limitation.

如果我們的記憶體是無限的, 就不必擔心洗掉 C++ 中的指標或 C# 中的垃圾回收. 然而, 記憶體是有限的, 因此我們的技術人員必須尋找對付這種限制的辦法.

The inclusion of ‘var’ into the C# language was done for a reason and bookmarks another iteration of C# (particularly C# 3.0). It allows us to spend less time telling the compiler what to do and more time thinking about the problem we are trying to solve.

將 "var" 包含在 C# 語言中是有原因的, 標志著 C# 的一次革新 (尤其是 C# 3.0). 它讓我們可以花更少的時間告訴編譯器應該做什么, 花更多的時間思考我們需要解決的問題.

Often I hear dogma like "use var only when using anonymous types." Why then should you use an anonymous type? Under these conditions you usually do not have a choice, such as when assigning variables to the results of LINQ expressions. Why do you not have a choice when using LINQ expressions? It's because the expression is accomplishing something more functional and typing concerns are the least of your worries.

經常聽到這樣的教條: "只能在使用匿名型別時才能 var." 那么為什么要使用匿名型別呢? 在這些情況下, 通常沒有選擇的余地, 比如在將變數分配給 LINQ 運算式的結果時. 為什么在使用 LINQ 運算式時沒得選? 這正是因為運算式實作了一些更為實用的功能, 且型別問題是最不需要擔心的.

In the ideal C# world, we would not have to put any words in front of a variable name at all. In fact, prefacing a variable with anything just confuses the developer even further, and allows for poor variable names to become a standard whereby everyone is reliant upon explicit type references.

在理想的 C# 編程環境中, 我們壓根就不需要在變數名前綴任何單詞. 實際上, 在變數前綴任何東西只會使開發者更加困惑, 并讓糟糕變數名成為每個開發者都在顯式依賴參考的標準.

Arguments against using ‘var’ (反對使用“var”的論據)

Some of the arguments I have heard against using ‘var’ and my responses to these are:

我看到一些反對使用 var 的論點, 對此我的回答是:

  • “It reduces clarity” – How? By removing the noise in front of a variable name, your brain has only one thing to focus on: the variable name. It increases clarity.

"它降低清晰度" - 為什么? 通過消除變數前面的噪音, 大腦只需要關注唯一的一件事: 變數名. 它增加了清晰度.

  • “It reduces readability and adds ambiguity” – This is similar to #1: readability can be increased by removing words in front of the variable and by choosing appropriate variable names and method names. Focusing on type distracts you from the real business problem you are trying to solve.

"它降低了可讀性, 同時增加了模糊性" - 這與第一條相似: 可讀性可以通過洗掉變數前面的單詞, 以及選擇適當的變數名和方法名來提高. 專注于型別會分散對要解決的實際業務問題的注意力.

  • “It litters the codebase” – This is usually an argument for consistency. If your codebase uses explicit type references everywhere, then by all means do not use ‘var’. Consistency is far more important. Either change all explicit references in the codebase to ‘var’ or do not use ‘var’ at all. This is a more general argument that applies to many more issues, such as naming conventions, physical organization policies, etc.

"它讓代碼庫變得亂糟糟" - 這大概是一致性的理由. 如果現存的代碼庫已經使用顯示型別參考, 那么別使用 var, 一致性更重要. 要么將代碼庫中所有顯示參考修改為 var, 要么從不使用 var. 這是個更普遍的觀點, 適用于很多情形, 比如命名約定, 物理檔案組織策略等等.

As a final thought, why do we preface interface names with “I” but not class names with “C” as we did in the days when Microsoft-C++ was the popular kid in school?

最后思考下, 當在 Microsoft C++ 在學校大受歡迎時, 為什么我們要在介面名前綴 "I" 而不在類名前綴 "C"?

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/6675.html

標籤:其他

上一篇:如何閱讀論文

下一篇:[譯文] C# 8 已成舊聞, 向前, 抵達 C# 9!

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more