读取对象属性时忽略NullReferenceException

是否有任何方法可以指示C#忽略一组语句的NullReferenceException (或任何特定的exception)。 当尝试从可能包含许多空对象的反序列化对象中读取属性时,这很有用。 有一个帮助方法来检查null可能是一种方法,但我正在寻找一个接近于’On Error Resume Next’(来自VB)的语句级别的块。

编辑:Try-Catch将跳过关于exception的后续语句

 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() ?? ""; 

这可以结合到:

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

现在我正在使用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) { } 

我会使用辅助方法。 关于错误恢复接下来只会导致疯狂。