C# 执行catch语句中的所有内容,而不抛出更多错误
我有一段代码,我试图一次对多个委托进行签名,但如果其中任何一个为null,我必须对所有其他委托进行签名C# 执行catch语句中的所有内容,而不抛出更多错误,c#,C#,我有一段代码,我试图一次对多个委托进行签名,但如果其中任何一个为null,我必须对所有其他委托进行签名 try { this.var1.asdf += ... this.var2.asdf += ... this.var3.asdf += ... this.var4.asdf += ... //and so on } catch { try { this.var1.asdf -= ... }catch{} try{
try
{
this.var1.asdf += ...
this.var2.asdf += ...
this.var3.asdf += ...
this.var4.asdf += ...
//and so on
}
catch
{
try {
this.var1.asdf -= ...
}catch{}
try{
this.var2.asdf -= ...
}catch{}
try{
this.var3.asdf -= ...
}catch{}
//and so on
}
我如何避免在大渔获量中的所有尝试捕获?我也不想使用“if not null语句”。我想继续处理catch块中的所有委托,不管它们是否会抛出null引用异常。所有行都需要在catch块内执行
有没有办法告诉catch不要再抛出任何错误并运行所有代码 不,没有,如果我需要做一些事情而忽略结果,我通常会编写一个try函数。忽略例外情况不是最佳做法,但我理解,有时候这样做是可以接受的:
public T Try(Action<T> action)
{
try
{
return action();
}
catch(Exception ex)
{
// Log the exception so you're at least aware of it
}
}
阅读了您的一条评论后,这可能是另一种不使用异常的方法:
public static void IfNotNull(this T value, Action<T> action)
{
if(value != null)
action(value);
}
基于@lan响应,无匿名方法:
try
{
this.var1.asdf += var1OnAsdf;
this.var2.asdf += var2OnAsdf;
this.var3.asdf += var3OnAsdf;
this.var4.asdf += var4OnAsdf;
//and so on
}
catch
{
TryUnregister(this.var1, var1OnAsdf);
TryUnregister(this.var2, var2OnAsdf);
TryUnregister(this.var3, var3OnAsdf);
//and so on
}
void TryUnregister(VarType var, DelegateType d)
{
if (var == null) return;
var.asdf -= d;
}
很好而且干净的解决方案。@NikolayKostov谢谢:)我在一些地方使用过它-通常我会注销一些东西,注意操作失败,但不会阻止执行继续。对于尝试删除不再使用的文件等操作非常有用。这真的很优雅!我必须记住这一点!很好的解决方案。是否有一些关键字类似于catch,只是它不会向外部抛出任何错误。试试{…}trap{…}好吧,trap只是一个例子,但你明白我的意思了。这太疯狂了,OP不想把
if(var1!=null)var1.asdf-=代码>因为将有20个if语句,但它们很乐意使用Try(()=>var1.asdf-=…)代码>20次!我会检查空值,而不是依赖异常。我希望避免10-20个不同的if语句。这对我来说是一种代码味道。必须有一个完整的其他方法来实现这一点。你能告诉我们更多关于你的用例吗?10-20个不同的变量,名字像var1..var20是一个明显的坏模式。不能对这些变量使用列表或数组吗?然后使用for循环检查空值,然后分配您的代理?@devhedgehog:我已经更新了我的答案,以建议异常的替代方案,但仍然使用扩展/lambda方法来执行空值检查。
var1.IfNotNull(v => v.asdf.DoSomething());
try
{
this.var1.asdf += var1OnAsdf;
this.var2.asdf += var2OnAsdf;
this.var3.asdf += var3OnAsdf;
this.var4.asdf += var4OnAsdf;
//and so on
}
catch
{
TryUnregister(this.var1, var1OnAsdf);
TryUnregister(this.var2, var2OnAsdf);
TryUnregister(this.var3, var3OnAsdf);
//and so on
}
void TryUnregister(VarType var, DelegateType d)
{
if (var == null) return;
var.asdf -= d;
}