今天同事問了我一個問題,像下面一樣的代碼為什么 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的時候會拋出異常。
自己寫了一下例子試了一下
的確是這樣的