6

有没有办法指示 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 消息中不存在 - XSD 中的一个可选元素)。现在我需要在访问叶元素之前检查层次结构中每个元素的 null 。即,在访问“ID”之前,我必须检查 instance[0]、prop1、prop2 是否不为空。

有没有更好的方法可以避免对层次结构中的每个元素进行空检查?

4

5 回答 5

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;
于 2008-11-18T06:40:37.923 回答
5

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

假设您正在尝试获取 myItem.MyProperty.GetValue() 的值,而 MyProperty 可能为空,并且您希望默认为空字符串:

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>");
于 2008-11-18T07:15:22.453 回答
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 没有单独的 try-catch 块 的每一行代码的想法

于 2008-12-14T12:24:04.773 回答
0
try
{
   // exceptions thrown here...
}
catch (NullReferenceException) { }
于 2008-11-18T06:42:17.187 回答
0

我会使用辅助方法。On Error Resume Next 只会导致疯狂。

于 2008-11-18T08:14:51.460 回答