久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

Equals(item, null) 或 item == null

Equals(item, null) or item == null(Equals(item, null) 或 item == null)
本文介紹了Equals(item, null) 或 item == null的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!

問題描述

是使用 static Object.Equals 來檢查null 比使用 == 運算符或 常規(guī) Object.Equals?后兩者是不是很容易被覆蓋,以至于檢查 null 不能按預(yù)期工作(例如,當(dāng)比較值 null 時返回 false)?

Is code that uses the static Object.Equals to check for null more robust than code that uses the == operator or regular Object.Equals? Aren't the latter two vulnerable to being overridden in such a way that checking for null doesn't work as expected (e.g. returning false when the compared value is null)?

換句話說,是這樣的:

if (Equals(item, null)) { /* Do Something */ }

比這更強大:

if (item == null) { /* Do Something */ }

我個人覺得后一種語法更容易閱讀.在編寫處理作者控制之外的對象(例如庫)的代碼時是否應(yīng)該避免?是否應(yīng)該始終避免(檢查空值時)?這只是頭發(fā)分裂嗎?

I personally find the latter syntax easier to read. Should it be avoided when writing code that will handle objects outside the author's control (e.g. libraries)? Should it always be avoided (when checking for null)? Is this just hair-splitting?

推薦答案

這個問題沒有簡單的答案.在我看來,任何說總是使用其中一種的人都給了你糟糕的建議.

There's no simple answer for this question. Anyone who says always use one or the other is giving you poor advice, in my opinion.

實際上可以調(diào)用幾種不同的方法來比較對象實例.給定兩個對象實例 ab,你可以這樣寫:

There are actually several different methods you can call to compare object instances. Given two object instances a and b, you could write:

  • Object.Equals(a,b)
  • Object.ReferenceEquals(a,b)
  • a.Equals(b)
  • a == b

這些都可以做不同的事情!

Object.Equals(a,b) 將(默認(rèn)情況下)對引用類型進行引用相等比較,并對值類型進行按位比較.來自 MSDN 文檔:

Object.Equals(a,b) will (by default) perform reference equality comparison on reference types and bitwise comparison on value types. From the MSDN documentation:

Equals 的默認(rèn)實現(xiàn)支持引用相等引用類型和按位相等對于值類型.引用相等表示對象引用是比較指的是同一個對象.按位相等意味著對象比較具有相同的二進制代表.

The default implementation of Equals supports reference equality for reference types, and bitwise equality for value types. Reference equality means the object references that are compared refer to the same object. Bitwise equality means the objects that are compared have the same binary representation.

請注意,派生類型可能將 Equals 方法覆蓋為實現(xiàn)價值平等.價值相等意味著被比較的對象具有相同的值但不同二進制表示.

Note that a derived type might override the Equals method to implement value equality. Value equality means the compared objects have the same value but different binary representations.

注意上面的最后一段......我們稍后會討論這個.

Note the last paragraph above ... we'll discuss this a bit later.

Object.ReferenceEquals(a,b) 僅執(zhí)行引用相等性比較.如果傳遞的類型是裝箱值類型,結(jié)果總是false.

a.Equals(b) 調(diào)用Object的虛實例方法,a的類型可以覆蓋做任何它想做的事情.調(diào)用是使用虛擬分派執(zhí)行的,因此運行的代碼取決于a的運行時類型.

a.Equals(b) calls the virtual instance method of Object, which the type of a could override to do anything it wants. The call is performed using virtual dispatch, so the code that runs depends on the runtime type of a.

a == b 調(diào)用a 的**編譯時類型* 的靜態(tài)重載運算符.如果該運算符的實現(xiàn)調(diào)用 ab 上的實例方法,則它還可能取決于參數(shù)的運行時類型.由于分派基于表達式中的類型,因此以下可能會產(chǎn)生不同的結(jié)果:

a == b invokes the static overloaded operator of the **compile-time type* of a. If the implementation of that operator invokes instance methods on either a or b, it may also depend on the runtime types of the parameters. Since the dispatch is based on the types in the expression, the following may yield different results:

Frog aFrog = new Frog();
Frog bFrog = new Frog();
Animal aAnimal = aFrog;
Animal bAnimal = bFrog;
// not necessarily equal...
bool areEqualFrogs = aFrog == bFrog;
bool areEqualAnimals = aAnimal = bAnimal;

所以,是的,使用 operator == 檢查空值存在漏洞. 實際上,大多數(shù)類型不會重載 == - 但永遠(yuǎn)沒有保證.

So, yes, there is vulnerability for check for nulls using operator ==. In practice, most types do not overload == - but there's never a guarantee.

實例方法 Equals() 在這里也好不到哪里去.雖然默認(rèn)實現(xiàn)執(zhí)行引用/按位相等性檢查,但類型可能會覆蓋 Equals() 成員方法,在這種情況下將調(diào)用此實現(xiàn).用戶提供的實現(xiàn)可以返回它想要的任何東西,即使與 null 相比也是如此.

The instance method Equals() is no better here. While the default implementation performs reference/bitwise equality checks, it is possible for a type to override the Equals() member method, in which case this implementation will be called. A user supplied implementation could return whatever it wants, even when comparing to null.

但是你問的 Object.Equals() 的靜態(tài)版本怎么樣?這最終可以運行用戶代碼嗎?好吧,事實證明答案是肯定的.Object.Equals(a,b) 的實現(xiàn)擴展為:

But what about the static version of Object.Equals() you ask? Can this end up running user code? Well, it turns out that the answer is YES. The implementation of Object.Equals(a,b) expands to something along the lines of:

((object)a == (object)b) || (a != null && b != null && a.Equals(b))

你可以自己試試:

class Foo {
    public override bool Equals(object obj) { return true; }  }

var a = new Foo();
var b = new Foo();
Console.WriteLine( Object.Equals(a,b) );  // outputs "True!"

因此,當(dāng)調(diào)用中的任何一種類型都不是 null 時,語句:Object.Equals(a,b) 可能會運行用戶代碼.請注意,當(dāng)任一參數(shù)為空時,Object.Equals(a,b) 不會調(diào)用 Equals() 的實例版本.

As a consequence, it's possible for the statement: Object.Equals(a,b) to run user code when neither of the types in the call are null. Note that Object.Equals(a,b) does not call the instance version of Equals() when either of the arguments is null.

簡而言之,您獲得的比較行為類型可能會有很大差異,具體取決于您選擇調(diào)用的方法.然而,這里有一條評論:Microsoft 沒有正式記錄 Object.Equals(a,b) 的內(nèi)部行為.如果您需要在不運行任何其他代碼的情況下將引用與 null 進行比較的鐵一般的保證,您需要 Object.ReferenceEquals():

In short, the kind of comparison behavior you get can vary significantly, depending on which method you choose to call. One comment here, however: Microsoft doesn't officially document the internal behavior of Object.Equals(a,b). If you need an iron clad gaurantee of comparing a reference to null without any other code running, you want Object.ReferenceEquals():

Object.ReferenceEquals(item, null);

此方法使意圖非常明確 - 您特別期望結(jié)果是兩個引用的比較以實現(xiàn)引用相等.與使用 Object.Equals(a,null) 之類的東西相比,這里的好處是以后不太可能有人過來說:

This method makes the intent extremently clear - you are specifically expecting the result to be the comparison of two references for reference equality. The benefit here over using something like Object.Equals(a,null), is that it's less likely that someone will come along later and say:

嘿,這很尷尬,讓我們將其替換為:a.Equals(null)a == null

可能會有所不同.

不過,讓我們在這里注入一些實用主義. 到目前為止,我們已經(jīng)討論了不同的比較方式產(chǎn)生不同結(jié)果的可能性.雖然情況確實如此,但在某些類型中,編寫 a == null 是安全的.StringNullable 等內(nèi)置 .NET 類具有定義明確的語義以進行比較.此外,它們是密封 - 防止通過繼承對其行為進行任何更改.以下是很常見的(而且是正確的):

Let's inject some pragmatism here, however. So far we've talked about the potential for different modalities of comparison to yield different results. While this is certainly the case, there are certain types where it's safe to write a == null. Built-in .NET classes like String and Nullable<T> have well defined semantics for comparison. Furthermore, they are sealed - preventing any change to their behavior through inheritance. The following is quite common (and correct):

string s = ...
if( s == null ) { ... }

寫是不必要的(而且很丑):

It's unnecessary (and ugly) to write:

if( ReferenceEquals(s,null) ) { ... }

因此在某些有限的情況下,使用 == 是安全且適當(dāng)?shù)?

So in certain limited cases, using == is safe, and appropriate.

這篇關(guān)于Equals(item, null) 或 item == null的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!

相關(guān)文檔推薦

How to check if String is null(如何檢查字符串是否為空)
Overriding == operator. How to compare to null?(覆蓋 == 運算符.如何與空值進行比較?)
What does the question mark in member access mean in C#?(成員訪問中的問號在 C# 中是什么意思?)
The || (or) Operator in Linq with C#(||(或)C# 中的 Linq 運算符)
C# null coalescing operator equivalent for c++(C# 空合并運算符等效于 C++)
How to make a value type nullable with .NET XmlSerializer?(如何使用 .NET XmlSerializer 使值類型可以為空?)
主站蜘蛛池模板: 99re在线视频 | 国产精品99久 | 红色av社区 | 国产精品一区二区久久 | 久久久久国产一区二区三区 | 亚洲综合第一页 | 亚洲成人一区 | 国产精品欧美日韩 | 国产成人精品一区二区三区四区 | 精品国产成人 | 久久久久久久久久久国产 | 一级看片 | 日韩一区二区免费视频 | 99视频 | 亚洲一区免费 | www.蜜桃av | 亚洲一区二区三区在线 | 国产精品欧美一区喷水 | 91一区二区| 91精品国产乱码久久久久久久久 | 久久精品亚洲精品国产欧美 | 9191成人精品久久 | 日韩精品在线观看一区二区三区 | av喷水 | 国产三级电影网站 | 黄视频网站免费观看 | 毛片在线看片 | 日本三级网址 | 国产在线一区二 | 伦理午夜电影免费观看 | 午夜免费电影 | 日韩毛片在线免费观看 | av大片在线观看 | 国产一区二区三区在线 | 中文字幕国 | 成人在线视频免费播放 | 淫片一级国产 | 国产精品a免费一区久久电影 | 日本精品视频在线观看 | 国产成人艳妇aa视频在线 | 天天干天天爱天天操 |