摘要:在.NET框架3.0或者3.5版本下,下面的代码会在GetHashCode时抛出NullReferenceException:
System.ComponentModel.SortDescription description = new System.ComponentModel.SortDescription();int hash = description.GetHashCode();
从设计指导:不要抛出NullReferenceException中,我们提到此准则至少包含两个方面的意思:
代码中决不要显性地 throw new NullReferenceException
代码中要有充分的错误检查,避免由CLR抛出NullReferenceException.
上面代码的问题是由于第一点,还是第二点呢?我们只有看到源代码才能确定。
在源代码中,我们看到对于这个public struct SortDescription,程序员定义了一个构造函数:
public SortDescription(string propertyName, ListSortDirection direction)
{
if (direction != ListSortDirection.Ascending && direction != ListSortDirection.Descending)
throw new InvalidEnumArgumentException("direction", (int)direction, typeof(ListSortDirection));
_propertyName = propertyName;
_direction = direction;
_sealed = false;
}
而GetHashCode的实现如下:
public override int GetHashCode()
{
return unchecked(PropertyName.GetHashCode() + Direction.GetHashCode());
}
其中PropertyName简单返回_propertyName. 您一定注意到,构造函数没有对propertyName是否为null做检查。 这是会导致GetHashCode时的NullReferenceException.
但是,我们最初的代码实际上使用的是struct结构的缺省构造函数。和class不同,即使程序员显式地提供了一个非缺省构造函数,struct仍然保有缺省构造函数。在设计库函数时,我们需要留意这些区别。
------ ------值此Blog 400篇之际,MSR Asis特制对联一幅, 以谢读者:
...[
阅读全文]