首页 > 学院 > 开发设计 > 正文

C#字符串连接Null时的一个小坑

2019-11-08 19:56:07
字体:
来源:转载
供稿:网友
C#里String.Concat方法有一个特别的地方,参数为Null时是不会抛出NullReferenceException异常的,而且,如果两个参数皆为Null,返回值是“”!有图有真相:MSDN上的解释:In string concatenation Operations, the C# compiler treats a null string the same as an empty string, but it does not convert the value of the original null string.stackoverflow上的相关问题虽然不是什么大坑,但还是值得mark一下,我本来是定义了几个类,因为需要放BindingList里头做数据源,定义的类重载了Equals方法和GetHashCode方法以方便查找,代码大概是这样的:
    public class Person    {        public string FirstName { get; set; }        public string SecondName { get; set; }        public int Age { get; set; }        public override bool Equals(object obj)        {            if (base.Equals(obj))                return true;            var d = obj as Person;            if (d == null)                return false;            return FirstName == d.FirstName && SecondName == d.SecondName;        }        public override int GetHashCode()        {            return string.Concat(FirstName, SecondName).GetHashCode();        }    }    public class Book    {        public string Id { get; set; }        public double PRice { get; set; }        public override bool Equals(object obj)        {            if (base.Equals(obj))                return true;            var d = obj as Book;            if (d == null)                return false;            return Id == d.Id;        }        public override int GetHashCode()        {            return Id.GetHashCode();        }    }

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表