1. 程式人生 > WINDOWS開發 >C# Linq中比較字串使用 Equals 為什麼報錯

C# Linq中比較字串使用 Equals 為什麼報錯

今天同事問了我一個問題,像下面一樣的程式碼為什麼s.BG_PriGroID 為null的時候報錯

objGroList = objGroList.Where(s => s.BG_PriGroID.Equals(pId)).ToList();

雖然我一直沒遇到這種錯誤,

(因為我一直用的==,我不常用Equals比較字串)

但是我還是想知道為什麼,然後我就找了一下微軟的線上原始碼https://referencesource.microsoft.com/

查了一下String.Equals,發現實現是下面這個樣子的

        public override bool Equals(Object obj) {
            
if (this == null) //this is necessary to guard against reverse-pinvokes and throw new NullReferenceException(); //other callers who do not use the callvirt instruction String str = obj as String; if (str == null) return false
; if (Object.ReferenceEquals(this,obj)) return true; if (this.Length != str.Length) return false; return EqualsHelper(this,str); }

原來.號前面的字串是null的時候會丟擲異常。

自己寫了一下例子試了一下

技術分享圖片

的確是這樣的