2010-08-05 56 views
3

我剛剛與我的一位同事討論了檢查空值的問題。關於檢查空值的問題

他發誓說:「在某些情況下,」下面的代碼想給他一個空值異常:

string test = null; 
if(test == null) //error here 
{ 

} 

但如果代碼更改爲這不會有什麼錯誤:

string test = null; 
if(null == test) //NO error here 
{ 

} 

我告訴過他這種事情沒有辦法發生,但他發誓固定他的代碼。有沒有可能出現上述變化可以解決錯誤的情況?

+0

尋呼Eric Lippert ... – 2010-08-05 18:39:08

+0

相關http://stackoverflow.com/questions/1264781/ – 2010-08-05 18:40:09

+0

平等,這是不可交換?害怕。 – Marc 2010-08-05 18:41:01

回答

12

不與字符串,不。你可以用寫的不好==超載這樣做雖然:

using System; 

public class NaughtyType 
{ 
    public override int GetHashCode() 
    { 
     return 0; 
    } 

    public override bool Equals(object other) 
    { 
     return true; 
    } 

    public static bool operator ==(NaughtyType first, NaughtyType second) 
    { 
     return first.Equals(second); 
    } 

    public static bool operator !=(NaughtyType first, NaughtyType second) 
    { 
     return !first.Equals(second); 
    } 
} 

public class Test 
{  
    static void Main() 
    { 
     NaughtyType nt = null; 
     if (nt == null) 
     { 
      Console.WriteLine("Hmm..."); 
     } 
    } 
} 

當然,如果你改變了等於運算符這樣的:

public static bool operator ==(NaughtyType first, NaughtyType second) 
{ 
    return second.Equals(first); 
} 

那麼你的同事的代碼會失敗,但你止跌」牛逼!基本上,如果你正確地重載運算符 - 或使用不會超載運算符的類型 - 這不是問題。如果你的同事不斷聲稱他遇到了問題,請讓他複製它。他當然不應該要求你減少可讀性(我相信大多數人會發現第一種形式更具可讀性)。

+0

「NaughtyType」,爸爸喜歡.... – 2010-08-05 18:45:54

1

if (test == null)如果測試是一個字符串的測試是有效的,將永遠不會例外。這兩項測試也基本完全相同。

+0

確實,否則string.IsNullOrEmpty()也會炸燬,這是不會發生的。 – 2010-08-05 18:41:52

+0

@Michael:好吧'string.IsNullOrEmpty' *可以*使用'object.ReferenceEquals'來實現...... – 2010-08-05 18:55:58

2

你說得對。如果他可以在沒有超載的==操作員的情況下重現此操作,請邀請他在此處發佈。

+0

是的,這是人們被教如何用C++編程(也可能是其他語言),因爲你可以在如果測試表達。你不能在c#中的if測試表達式中輕鬆賦值,所以不需要樣式。 – 2010-08-05 18:42:11

6

我認爲這是一個遺留的從C/C一個「最佳實踐」 ++,因爲使用「=」,而不是「==」是一個容易犯錯誤:

if(test = null) // C compiler Warns, but evaluates always to false 

if(null = test) // C compiler error, null cannot be assigned to 

在C# ,它們都會產生錯誤。

+1

即使經過許多多年的編程,同意這個愚蠢的錯誤總是會讓我感受到C/C++代碼。 C#不會讓它發生:=) – Justin 2010-08-05 19:03:34

+2

是的,我懷疑有人聲稱「編碼錯誤」,以試圖促進他的編碼偏好。 – 2010-08-05 19:18:09