【问题标题】:Setting inner exception with activator, C#, Postsharp使用激活器、C#、Postsharp 设置内部异常
【发布时间】:2012-07-18 16:01:01
【问题描述】:

编写包含 A 类型异常并将其输出为 B 类型的 postsharp aspect。这在某些情况下是常见的模式,因此这应该会删除大部分样板文件。问题是,使用激活器创建异常时如何设置内部异常?

namespace PostSharpAspects.ExceptionWrapping
{
    [Serializable]
    public class WrapExceptionsAttribute : OnMethodBoundaryAspect
    {
        private readonly Type _catchExceptionType;
        private readonly Type _convertToType;

        public WrapExceptionsAttribute(Type catchTheseExceptions, Type convertThemToThisType)
        {
            _catchExceptionType = catchTheseExceptions;
            _convertToType = convertThemToThisType;
        }

        public override void OnException(MethodExecutionArgs args)
        {
            if (args.Exception.GetType() == _catchExceptionType)
            {
                throw (Exception) Activator.CreateInstance(_convertToType);
            }
        }
    }
}

如果我尝试设置内部异常: throw (Exception) Activator.CreateInstance(_convertToType, args.Exception);

我收到 xxxx 类型异常没有为其定义构造函数的错误,如何解决这个问题?我必须使用某种反射技巧来编写私有字段吗?

【问题讨论】:

    标签: c# .net postsharp


    【解决方案1】:

    使用 Type.GetConstructor(Type[]) 获取适当的异常构造函数。 http://msdn.microsoft.com/en-us/library/h93ya84h.aspx

    类似这样的:

    throw (Exception)_convertToType
        .GetConstructor(new Type[]{ typeof(string), typeof(Exception) })
        .Invoke(new object[]{ _catchExceptionType });
    

    【讨论】:

    • 需要实际工作版本.GetConstructor(new [] {typeof(string), typeof(Exception)}),但你让我走对了,谢谢:)
    • 太棒了!我已经更新了答案以反映正确的构造函数。
    猜你喜欢
    • 2014-11-09
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 2014-08-30
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多