2016-02-17 53 views
0

我最近發現:拋出一個異常,如果一個對象爲空

if (Foo() != null)  
    { mymethod(); } 

可以改寫爲

Foo?.mymethod() 

可在下列以類似的方式被改寫?

if (Foo == null) 
{ throw new Exception()} 
+0

你擁有它的方式是正確的。 [空條件運算符](https://msdn.microsoft.com/en-us/library/dn986595.aspx)只返回NULL。 – Steve

+1

有沒有捷徑可以拋出異常,但你可以做的事情之一是縮短檢查,如「if(Foo == null || Foo.Bar == null || Foo.Bar.Oof == null)throw ...如果(Foo?.Bar?.Oof == null)拋出...' – Mark

回答

1

我不知道你爲什麼會...

public Exception GetException(object instance) 
{ 
    return (instance == null) ? new ArgumentNullException() : new ArgumentException(); 
} 

public void Main() 
{ 
    object something = null; 
    throw GetException(something); 
} 
2

有在C#中沒有類似的方式語法6

但是,如果你願意,你可以使用簡化空檢查擴展方法...

public static void ThrowIfNull(this object obj) 
    { 
     if (obj == null) 
      throw new Exception(); 
    } 

使用

foo.ThrowIfNull(); 

或改進它顯示空對象名稱。

public static void ThrowIfNull(this object obj, string objName) 
{ 
    if (obj == null) 
     throw new Exception(string.Format("{0} is null.", objName)); 
} 

foo.ThrowIfNull("foo"); 
使用空條件
+0

方法調用可以改爲: foo.ThrowIfNull(nameof(foo)); 如果變量名稱被更改,使其安全:) –

2

If null then null; if not then dot

代碼可以通過閱讀時說,聲明自己是很容易理解。例如在你的例子中,如果foo爲null,那麼它將返回null。如果它不爲空,那麼它會「點」,然後拋出一個我不相信的異常就是你想要的。

如果你正在尋找一種速記方式來處理空檢查,我會推薦Jon Skeet's answer here和他的相關blog post關於這個話題。

Deborah Kurata在我推薦的this Pluralsight course中引用了這種說法。

相關問題