代码之家  ›  专栏  ›  技术社区  ›  DxCK

postsharp:派生类的构造函数的onMethodBoundarySpect

  •  1
  • DxCK  · 技术社区  · 16 年前

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

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

    这是设计的吗?这是虫子吗? 还是我做错了什么?

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

    [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.");
            }
        }
    }
    

    输出是:

    在主服务器上捕获异常。

    2 回复  |  直到 16 年前
        1
  •  2
  •   Gael Fraiteur    16 年前

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

        2
  •  0
  •   Mark Coleman    16 年前

    如果你看 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();
    }
    

    如果要处理方面继承,请看使用 MulticastAttributeUsage

    推荐文章