usm*_*een 5 .net c# serialization language-features exception
是否有任何方法可以指示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) { }
Run Code Online (Sandbox Code Playgroud)
例如:我将XML消息反序列化为对象,然后尝试访问类似的属性
Message.instance[0].prop1.prop2.ID
Run Code Online (Sandbox Code Playgroud)
现在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!");
}
Run Code Online (Sandbox Code Playgroud)
除此之外 - 也许有些使用条件运算符?
string name = obj == null ? "" : obj.Name;
Run Code Online (Sandbox Code Playgroud)
三元运算符和/或 ?? 运算符可能有用。
假设您正在尝试获取 myItem.MyProperty.GetValue() 的值,而 MyProperty 可能为 null,并且您希望默认为空字符串:
string str = myItem.MyProperty == null ? "" : myItem.MyProperty.GetValue();
Run Code Online (Sandbox Code Playgroud)
或者在 GetValue 的返回值为 null 的情况下,但您想默认为某些内容:
string str = myItem.MyProperty.GetValue() ?? "<Unknown>";
Run Code Online (Sandbox Code Playgroud)
这可以组合为:
string str = myItem.MyProperty == null
? ""
: (myItem.MyProperty.GetValue() ?? "<Unknown>");
Run Code Online (Sandbox Code Playgroud)
现在我正在使用委托和 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 "";
}
}
Run Code Online (Sandbox Code Playgroud)
感谢 Try-catch 每一行代码,无需单独的 try-catch 块的 想法
| 归档时间: |
|
| 查看次数: |
6394 次 |
| 最近记录: |