PostSharp:派生类构造函数的OnMethodBoundaryAspect

时间:2009-12-11 12:24:15

标签: c# .net inheritance constructor postsharp

我有一个方面在异常时向控制台写入内容。 我有一个基类,它的构造函数抛出一个异常,一个派生类在它的构造函数上有方面。

我希望构造函数上的派生类方面将捕获基类异常,但它不会。

这是设计的吗?这是一个错误吗? 或者我做错了什么?

以下是示例代码(控制台应用程序):

[Serializable]
public class OnExceptionWriteAspect : OnMethodBoundaryAspect
{
    public override void OnException(MethodExecutionEventArgs eventArgs)
    {
        Console.WriteLine("Exception catched on Aspect.");
    }
}

public class BaseClass
{
    public BaseClass()
    {
        throw new Exception();
    }
}

public class DerivedClass : BaseClass
{
    [OnExceptionWriteAspect]
    public DerivedClass()
        : base()
    {

    }
}

public class Program
{
    static void Main(string[] args)
    {
        try
        {
            new DerivedClass();
        }
        catch
        {
            Console.WriteLine("Exception catched on Main.");
        }
    }
}

输出结果为:

  

Main上有异常。

2 个答案:

答案 0 :(得分:2)

这是设计的。无法在对基础构造函数的调用周围放置异常处理程序。 MSIL代码无法验证。

答案 1 :(得分:0)

如果您查看DerivedClass via反射器,您会看到Aspect只包含DerivedClass的构造函数。

public class DerivedClass : BaseClass
{
    // Methods
    public DerivedClass()
    {
        MethodExecutionEventArgs ~laosEventArgs~1;
        try
        {
            ~laosEventArgs~1 = new MethodExecutionEventArgs(<>AspectsImplementationDetails_1.~targetMethod~1, this, null);
            <>AspectsImplementationDetails_1.MyTest.OnExceptionWriteAspect~1.OnEntry(~laosEventArgs~1);
            if (~laosEventArgs~1.FlowBehavior != FlowBehavior.Return)
            {
                <>AspectsImplementationDetails_1.MyTest.OnExceptionWriteAspect~1.OnSuccess(~laosEventArgs~1);
            }
        }
        catch (Exception ~exception~0)
        {
            ~laosEventArgs~1.Exception = ~exception~0;
            <>AspectsImplementationDetails_1.MyTest.OnExceptionWriteAspect~1.OnException(~laosEventArgs~1);
            switch (~laosEventArgs~1.FlowBehavior)
            {
                case FlowBehavior.Continue:
                case FlowBehavior.Return:
                    return;
            }
            throw;
        }
        finally
        {
            <>AspectsImplementationDetails_1.MyTest.OnExceptionWriteAspect~1.OnExit(~laosEventArgs~1);
        }
    }
}

public BaseClass()
{
    throw new Exception();
}

如果要处理Aspect继承,请查看使用MulticastAttributeUsage