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