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

Equals(item, null) 或 item == null

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

問題描述

是使用 static Object.Equals 來檢查null 比使用 == 運算符或 常規 Object.Equals?后兩者是不是很容易被覆蓋,以至于檢查 null 不能按預期工作(例如,當比較值 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 */ }

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

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.

實際上可以調用幾種不同的方法來比較對象實例.給定兩個對象實例 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) 將(默認情況下)對引用類型進行引用相等比較,并對值類型進行按位比較.來自 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 的默認實現支持引用相等引用類型和按位相等對于值類型.引用相等表示對象引用是比較指的是同一個對象.按位相等意味著對象比較具有相同的二進制代表.

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 方法覆蓋為實現價值平等.價值相等意味著被比較的對象具有相同的值但不同二進制表示.

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) 僅執行引用相等性比較.如果傳遞的類型是裝箱值類型,結果總是false.

a.Equals(b) 調用Object的虛實例方法,a的類型可以覆蓋做任何它想做的事情.調用是使用虛擬分派執行的,因此運行的代碼取決于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 調用a 的**編譯時類型* 的靜態重載運算符.如果該運算符的實現調用 ab 上的實例方法,則它還可能取決于參數的運行時類型.由于分派基于表達式中的類型,因此以下可能會產生不同的結果:

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 == 檢查空值存在漏洞. 實際上,大多數類型不會重載 == - 但永遠沒有保證.

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() 在這里也好不到哪里去.雖然默認實現執行引用/按位相等性檢查,但類型可能會覆蓋 Equals() 成員方法,在這種情況下將調用此實現.用戶提供的實現可以返回它想要的任何東西,即使與 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() 的靜態版本怎么樣?這最終可以運行用戶代碼嗎?好吧,事實證明答案是肯定的.Object.Equals(a,b) 的實現擴展為:

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!"

因此,當調用中的任何一種類型都不是 null 時,語句:Object.Equals(a,b) 可能會運行用戶代碼.請注意,當任一參數為空時,Object.Equals(a,b) 不會調用 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.

簡而言之,您獲得的比較行為類型可能會有很大差異,具體取決于您選擇調用的方法.然而,這里有一條評論:Microsoft 沒有正式記錄 Object.Equals(a,b) 的內部行為.如果您需要在不運行任何其他代碼的情況下將引用與 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);

此方法使意圖非常明確 - 您特別期望結果是兩個引用的比較以實現引用相等.與使用 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

可能會有所不同.

不過,讓我們在這里注入一些實用主義. 到目前為止,我們已經討論了不同的比較方式產生不同結果的可能性.雖然情況確實如此,但在某些類型中,編寫 a == null 是安全的.StringNullable 等內置 .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) ) { ... }

因此在某些有限的情況下,使用 == 是安全且適當的.

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

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

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

相關文檔推薦

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 使值類型可以為空?)
主站蜘蛛池模板: 精品视频在线播放 | 欧美日韩在线成人 | 国产精品久久亚洲7777 | 91天堂网 | 久久免费视频1 | www.三级 | 天堂av在线影院 | 欧美在线一区二区三区 | 亚洲视频一区二区三区四区 | 男女羞羞视频在线免费观看 | 精品国产欧美 | 亚洲天堂中文字幕 | 国产免费一区 | 欧美一区二区在线 | 欧美久久免费观看 | 国产精品久久久久久妇女6080 | 久久成人综合 | 国产精品一区二区久久久久 | 成人精品国产免费网站 | 国产精品成人一区二区三区夜夜夜 | 精精国产xxxx视频在线播放 | 久久高清免费视频 | 天天在线操 | 亚洲一区二区三区视频 | 2023亚洲天堂 | 国产 日韩 欧美 在线 | 九九热热九九 | 四虎影院久久 | 成人午夜激情 | 亚洲欧美国产精品久久 | av免费看在线 | 91超碰在线| 欧美精品网站 | 久久精品av | 少妇一级淫片免费播放 | 亚洲精品无人区 | aaaaaaa片毛片免费观看 | 欧美极品少妇xxxxⅹ免费视频 | www.亚洲| 日本成人二区 | 久久久观看 |