3
我列出了五種不同的場景,我認爲產品代碼中需要進行空值檢查。雖然,我查過的大部分參考書都沒有做這種檢查。忽略這些檢查是合理的,而原始參考試圖提供其他重要想法。在這裏,我總結了我的所有疑慮,如有錯誤,請糾正我。這些是否需要檢查傳入參數?
class Student
{
public string Name { get; set; }
public Student(string name)
{
Name = name;
}
public Student() { }
public override string ToString()
{
return string.Format("Name: {0}", Name);
}
}
class StudentNameComparer : IComparer<Student>
{
public int Compare(Student x, Student y)
{
if ((x == null) || (y == null)) // <C1> Should we check there?
throw new ArugmentNullException("bla bla");
return x.Name.CompareTo(y.Name);
}
}
////////////////////////////////////////////////////
List<Student> students = new List<Student> {
new Student("s1"),
new Student("s4"),
new Student("s3"),
new Student("s2")
};
students.Sort(delegate(Student x, Student y)
{
if ((x == null) || (y == null)) // <C2> Should we check there?
throw new ArugmentNullException("bla bla");
return x.Name.CompareTo(y.Name);
});
////////////////////////////////////////////////////
List<Student> students = new List<Student> {
new Student("s1"),
new Student("s4"),
new Student("s3"),
new Student("s2")
};
students.Sort((x, y) =>
{
if ((x == null) || (y == null)) // <C3-1> Should we check there?
throw new ArugmentNullException("bla bla");
return x.Name.CompareTo(y.Name);
});
Or
students.Sort((Student x, Student y) =>
{
if ((x == null) || (y == null)) // <C3-2> Should we check there?
throw new ArugmentNullException("bla bla");
return x.Name.CompareTo(y.Name);
});
////////////////////////////////////////////////////
List<Student> students = new List<Student> {
new Student("s1"),
new Student("s4"),
new Student("s3"),
new Student("s2")
};
foreach (Student std in students.OrderBy(p =>
{
if (p == null) // <C4> Should we check there?
{
throw new ArgumentNullException("...");
}
return p.Name;
}))
{
Console.WriteLine(std);
}
我很困惑。在C#深度第2頁的第10頁中提到了類似的代碼。 – q0987 2011-05-30 23:46:10
困惑什麼具體?那麼比較就不能拋出'null',其他大部分檢查都是沒有意義的。 – Joey 2011-05-30 23:56:03