問題描述
有沒有更好的方法來忽略 C# 中的異常,而不是將其放在 try catch 塊中并且在 catch 中什么也不做?我發現這種語法很麻煩.對于代碼塊,我不能簡單地標記"它,以便運行時知道要忽略哪些異常嗎?
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 { }
}
使用方法如下:
IgnoreExceptions(() => foo());
另一種解決方案是使用 AOP(面向方面??編程) - 有一個名為 PostSharp 的工具可以讓您創建一個可以捕獲特定程序集/類/方法中所有異常的屬性,這更接近您要查找的內容.
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# 中的異常的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!