加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 执行catch语句中的所有内容,而不会抛出更多错误

发布时间:2020-12-15 23:45:31 所属栏目:百科 来源:网络整理
导读:我有一段代码,我尝试一次签署许多代表,但如果其中任何一个为null,我必须取消所有其他代理. try{ this.var1.asdf += ... this.var2.asdf += ... this.var3.asdf += ... this.var4.asdf += ... //and so on}catch{ try { this.var1.asdf -= ... }catch{} try{
我有一段代码,我尝试一次签署许多代表,但如果其中任何一个为null,我必须取消所有其他代理.

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 statements”.我想继续在catch块内的所有委托,无论它们是否可能抛出空引用异常.所有行都需要在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
   }
}

然后,您可以按以下行调用它:

Try(() => { var1.asdf.DoSomething(); });

阅读了您的一条评论后,这可能是另一种不使用异常的方法:

public static void IfNotNull(this T value,Action<T> action)
{
   if(value != null)
      action(value);
}

然后你可以调用,这使得在代码中执行null检查并防止任何异常(顺便说一下,这很慢)

var1.IfNotNull(v => v.asdf.DoSomething());

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读