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

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

问题描述

有没有更好的办法忽略在C#中不是把它在一个try catch块,无所事事中捕捉异常?我觉得这个语法很麻烦。对于codeblock和不能我只是标签,它以这样一种方式使运行时知道哪些异常怠慢?

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?

推荐答案

我不认为这是一个办法来避免异常,但你可以用下面的code片断:

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 { }
}

使用方法如下:

IgnoreExceptions(() => foo());

另一种解决方案是使用AOP(面向方面​​编程) - 有一个叫做工具 PostSharp ,使您可以创建一个属性,它会夹在特定的组装/类/方法的所有异常这是更接近你要找的是什么

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

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

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