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的時候會拋出異常。

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

 

 的確是這樣的


免責聲明!

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



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