忽略C#中的异常 [英] Ignore Exception in C#

查看:175
本文介绍了忽略C#中的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更好的方法来忽略C#中的异常,而不是把它放在一个try catch块中,什么也不做catch?我发现这个语法很麻烦。对于一个代码块,我不能简单地以这样的方式标记它,以便运行时知道哪些异常被忽略?

解决方案

我不认为有一个技巧来避免异常,但你可以使用以下代码片段:

  public void IgnoreExceptions行动行为)
{
try
{
act.Invoke();
}
catch {}
}

像:

  IgnoreExceptions(()=> foo()); 

另一个解决方案是使用AOP(面向对象编程) - 有一个名为 PostSharp ,它使您能够创建一个属性,该属性将捕获特定程序集/类/方法中的所有异常,该属性更接近于重新寻找。


Is there a better way to ignore an exception in C# than putting it up in a try catch block and doing nothing in catch? I find this syntax to be cumbersome. For a codeblock, can't I simply "tag" it in such a way so as runtime knows which exceptions to neglect?

解决方案

I don't think there is a trick to avoid exception but you can use the following code snippet:

public void IgnoreExceptions(Action act)
{
   try
   {
      act.Invoke();
   }
   catch { }
}

Using the method looks like:

IgnoreExceptions(() => foo());

Another solution is to use AOP (Aspect Oriented Programming) - there's a tool called PostSharp which enables you to create an attribute that would catch all exceptions in specific assembly/class/method, which is closer to what you're looking for.

这篇关于忽略C#中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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