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的时候会抛出异常。

自己写了一下例子试了一下

 

 的确是这样的

posted @ 2020-06-11 19:29  fgnu  阅读(964)  评论(0编辑  收藏  举报