簡體   English   中英

讀取對象屬性時忽略NullReferenceException

[英]Ignore NullReferenceException when reading object properties

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

編輯:Try-Catch將跳過關於異常的后續語句

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 Message中 - XSD中的可選元素)。 現在我需要在訪問葉元素之前檢查層次結構中每個元素的null。 即在訪問“ID”之前,我要檢查實例[0],prop1,prop2是否為空。

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

簡而言之:沒有。 在嘗試使用之前,請先檢查參考。 這里有一個有用的技巧可能是C#3.0擴展方法......它們允許你出現在空引用上調用某些內容而不會出現錯誤:

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

除此之外 - 也許有些使用條件運算符?

string name = obj == null ? "" : obj.Name;

三元運算符和/或?? 運算符可能有用。

假設您正在嘗試獲取myItem.MyProperty.GetValue()的值,並且MyProperty可能為null,並且您希望默認為空字符串:

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

或者,如果GetValue的返回值為null,但您希望默認為某些內容:

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

這可以結合到:

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

現在我正在使用delegate和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每行代碼,沒有單獨的try-catch塊來實現這個想法

try
{
   // exceptions thrown here...
}
catch (NullReferenceException) { }

我會使用輔助方法。 關於錯誤恢復接下來只會導致瘋狂。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM