2011-05-30 66 views
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); 
} 

回答

4

那麼,只要看看接口in the documentation

實際上,在IComparer中做了什麼是錯誤的。

首選實現是使用其中一個參數的CompareTo方法。

允許將null與任何類型進行比較,並且在使用IComparable時不會生成異常。排序時,null被認爲比任何其他對象都少。

因此Compare()不能因爲其中一個元素是null而拋出。

由於我們確定,Sort方法不需要檢查,因爲我們可以在上面看到null很好。

不知道最後一個例子。我相信在這種情況下投擲會有點嚴厲。但是,無論如何,null s應該不會出現在您的收藏中。如果我至少有一個學生名單,那麼在那裏包含null就沒有多大意義了。

喜歡的東西

p => p != null ? p.Name : string.Empty 

可以使用(這是與默認情況下強加給null值排序一致)。

+0

我很困惑。在C#深度第2頁的第10頁中提到了類似的代碼。 – q0987 2011-05-30 23:46:10

+0

困惑什麼具體?那麼比較就不能拋出'null',其他大部分檢查都是沒有意義的。 – Joey 2011-05-30 23:56:03