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

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

问题描述

对于一组语句,有没有办法引导C#忽略 NullReferenceException (或任何特定的异常)。
当尝试从可能包含许多空对象的反序列化对象读取属性时,这是有用的。
有一个帮助方法来检查null可能是一种方式,但我正在寻找一个接近On Error Resume Next(从VB开始)的一些语句级别的东西。



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

  try 
{
stmt 1; // NullReferenceException这里,将跳到catch - 跳过stmt2和stmt 3
stmt 2;
stmt 3;
}
catch(NullReferenceException){}

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

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

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



有没有更好的方法来避免空值检查对于层次结构中的每个元素?

解决方案

现在我使用delegate和NullReferenceException处理

  public delegate string SD(); //在类定义之前声明

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

// GetValue defintion
私有字符串GetValue(SD d){
try
{
return d();
}
catch(NullReferenceException){
return;
}

}

感谢
< a href =https://stackoverflow.com/questions/117173/c-try-catch-every-line-of-code-without-individual-try-catch-blocks>尝试捕获每行代码,而无需个别try-catch块
的想法


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.

EDIT: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) { }

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

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?

解决方案

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

    }

Thanks to Try-catch every line of code without individual try-catch blocks for the idea

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

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