使用C#属性处理异常

Edi*_*ang 6 c# attributes

我想可以使用Attribute进行异常处理,而不是在每个方法中写"try ... catch".

例如,现在,我的每个方法都是这样的:

public void DoSomething()
{
    try
    {
        // do something
    }
    catch (Exception ex)
    {
        // exception handling rules, always the same.
        throw;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要:

[HandleException]
public void DoSomething()
{
    // do something
}
Run Code Online (Sandbox Code Playgroud)

可能吗?

avi*_*ivr 3

这可以通过 AOP(面向方面​​编程)来完成。PostSharp 是实现此目的的框架之一。请参阅示例http://www.sharpcrafters.com/solutions/exception