2008-11-18 69 views
4

是否有任何方式指示C#忽略NullReferenceException(或針對該問題的任何特定異常)。 當試圖讀取可能包含許多空對象的反序列化對象的屬性時,這非常有用。 有一個幫助方法來檢查null可能是一種方法,但我正在尋找一些接近'On Error Resume Next'(來自VB)在語句級別的塊。閱讀對象屬性時忽略NullReferenceException

編輯:嘗試捕獲將跳過例外隨後聲明

try 
{ 
    stmt 1;// NullReferenceException here, will jump to catch - skipping stmt2 and stmt 3 
    stmt 2; 
    stmt 3; 
} 
catch (NullReferenceException) { } 

例如:我反序列化XML消息到一個對象,然後嘗試訪問屬性像

Message.instance[0].prop1.prop2.ID 

現在prop2可以是一個空對象(因爲它不存在於XML消息 - XSD中的可選元素)。現在我需要在訪問葉元素之前檢查層次結構中每個元素的空值。即我必須在訪問'ID'之前檢查實例[0],prop1,prop2是否爲空。

有沒有更好的方法避免對層次結構中的每個元素進行空值檢查?

回答

1

現在我使用的委託和NullReferenceException異常處理

public delegate string SD();//declare before class definition 

string X = GetValue(() => Message.instance[0].prop1.prop2.ID); //usage 

//GetValue defintion 
private string GetValue(SD d){ 
     try 
     { 
      return d(); 
     } 
     catch (NullReferenceException) { 
      return ""; 
     } 

    } 

由於 Try-catch every line of code without individual try-catch blocks 爲理念

6

總之:沒有。在嘗試使用它之前仔細檢查參考。這裏的一個有用的技巧可能是C#3.0的擴展方法......他們讓你出現對空引用調用的東西沒有錯誤:

string foo = null; 
foo.Spooky(); 
... 
public static void Spooky(this string bar) { 
    Console.WriteLine("boo!"); 
} 

比其他 - 也許有些使用條件運算符的?

string name = obj == null ? "" : obj.Name; 
0
try 
{ 
    // exceptions thrown here... 
} 
catch (NullReferenceException) { } 
+0

除非你需要,對於每一個可能拋出線... – 2008-11-18 06:43:09

4

三元運營商和/或??運營商可能會有用。

說你是試圖讓myItem.MyProperty.GetValue()的值,並且可以myProperty的爲空,並且要爲默認爲空字符串:

string str = myItem.MyProperty == null ? "" : myItem.MyProperty.GetValue(); 

或在情況下返回的GetValue的值是空的,但你要默認的東西:

string str = myItem.MyProperty.GetValue() ?? "<Unknown>"; 

這可以結合起來:

string str = myItem.MyProperty == null 
    ? "" 
    : (myItem.MyProperty.GetValue() ?? "<Unknown>"); 
0

我會用輔助方法。在錯誤恢復下一個只會導致瘋狂。