1

我有一个方面可以在异常时向控制台写入一些内容。我有一个在其构造函数上引发异常的基类,以及一个在其构造函数上具有方面的派生类。

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

这是设计使然吗?这是一个错误吗?还是我做错了什么?

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

[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 上捕获的异常。

4

2 回答 2

2

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

于 2009-12-11T19:35:04.893 回答
0

如果您查看DerivedClassvia 反射器,您会发现 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 Inheritance,请查看使用MulticastAttributeUsage

于 2009-12-11T15:24:44.167 回答