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

C#里String.Concat方法有一个特别的地方,参数为Null时是不会抛出NullReferenceException异常的,而且,如果两个参数皆为Null,返回值是“”!有图有真相:
C#字符串连接Null时的一个小坑_第1张图片
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();         }     }

 
  
 
 

你可能感兴趣的:(Mark,C#)