阅读对象属性时忽略的NullReferenceException [英] Ignore NullReferenceException when reading object properties

查看:143
本文介绍了阅读对象属性时忽略的NullReferenceException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法直接C#忽略的NullReferenceException (或与此有关的任何特定的异常)的一组语句。 试图读取可能包含了很多空对象反序列化对象的属性时,这是非常有用的。 有一个辅助的方法来检查空可能是一种方式,但是我正在寻找一些接近在错误恢复下一步'(从VB)在语句级别的块。

Is there any way to direct C# to ignore NullReferenceException (or any specific exception for that matter) for a set of statements. This is useful when trying to read properties from a deserialized object that may contain many null objects in it. Having a helper method to check for null could be one way but I'm looking for something close to 'On Error Resume Next' (from VB) at a block of statement level.

编辑:尝试捕获将跳过异常后续语句

Try-Catch will skip the succeeding statements on exception

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

例如:我反序列化的XML消息到一个对象,然后尝试访问属性像

For Example: I'm deserializing an XML message to an object and then try to access a property like

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

现在prop2可以是一个空对象(因为它不存在于XML的消息 - XSD中的可选元素)。现在我需要访问叶元素之前,检查空的层次结构中的每个元素。即我已经检查是否实例[0],为prop1,prop2不为空,访问ID之前。

now prop2 could be a null object (because it doesn't exists in XML Message - an optional element in XSD). right now I need to check for null for each element in the hierarchy before accessing the leaf element. i.e I've to check if instance[0], prop1, prop2 are not null, before accessing 'ID'.

有没有更好的办法,避免无效检查的层次结构中的每一个元素?

Is there a better way that avoids null-checking for each element in the hierarchy?

推荐答案

现在我使用的是委托和NullReferenceException异常处理

now I'm using delegate and NullReferenceException handling

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 "";
        }

    }

感谢 <一href="http://stackoverflow.com/questions/117173/c-try-catch-every-line-of-$c$c-without-individual-try-catch-blocks">http://stackoverflow.com/questions/117173/c-try-catch-every-line-of-$c$c-without-individual-try-catch-blocks 为理念

Thanks to http://stackoverflow.com/questions/117173/c-try-catch-every-line-of-code-without-individual-try-catch-blocks for the idea

这篇关于阅读对象属性时忽略的NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆