使用属性处理类库中的异常 [英] Handle Exception in Class Library with Attribute

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

问题描述

在类库中,我正在尝试使用类库中的属性处理异常。有没有AOP(PostSharp)的方法吗?

In a class Library, I am trying to handle exception with Attributes in Class Library. Is there a way to do without AOP (PostSharp) ?

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class HandleError : Attribute
{

    public void OnException(){
    try {

    }
    catch (Exception) {

    }}
}

想要装饰这样的属性。

[HandleError]
public void SampleMethod()
{
  throw new Exception();
}


推荐答案

简单地说,您可以容易。您可以使用其他库中的AOP(例如, Spring.NET )。唯一的区别是Spring.NET在运行时运行,而Postsharp在编译时运行。

Simply put, you can't easily. You could use AOP from another library (for example Spring.NET). The only difference would be that Spring.NET works at runtime, while Postsharp works at compile time.

您甚至可以使用 Fody 在编译时进行一些代码重写,例如PostSharp。

You could even use Fody to do some code rewriting at compile time, like PostSharp.

请注意,如果您只是想对异常进行一些登录,而无需从堆栈中删除该异常(您不想吃掉它或对其进行更改),则只需添加 FirstChanceException 处理程序。请注意,这将大大降低所有速度,因为您将需要使用反射来检查属性的存在。而且,如果您想走栈,它会变得更慢! (更复杂)

Note that if you simply want to do some logging on an exception and you don't need to remove the exception from the stack (you don't want to "eat" it or change it), then you could simply add a FirstChanceException handler. Note that this would slow quite much everything, because you would need to use reflection to check for the presence of the attribute. And if you wanted to walk the stack it would become even slower! (and much more complex)

这篇关于使用属性处理类库中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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