Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用activator、C#、Postsharp设置内部异常_C#_.net_Postsharp - Fatal编程技术网

使用activator、C#、Postsharp设置内部异常

使用activator、C#、Postsharp设置内部异常,c#,.net,postsharp,C#,.net,Postsharp,编写封装类型异常并将其作为B类型输出的postsharp方面。在某些情况下,这是一种常见的模式,所以这应该会删除很多样板文件。问题是,在使用activator创建异常时,如何设置内部异常 namespace PostSharpAspects.ExceptionWrapping { [Serializable] public class WrapExceptionsAttribute : OnMethodBoundaryAspect { private re

编写封装类型异常并将其作为B类型输出的postsharp方面。在某些情况下,这是一种常见的模式,所以这应该会删除很多样板文件。问题是,在使用activator创建异常时,如何设置内部异常

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);
            }
        }
    }
}
如果我尝试设置内部异常,请执行以下操作: 抛出(异常)Activator.CreateInstance(_convertToType,args.Exception)

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

使用Type.GetConstructor(Type[])来获取适当的异常构造函数

大概是这样的:

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

需要实际的工作版本。GetConstructor(新[]{typeof(string),typeof(Exception)}),但是你让我做对了,谢谢:)太棒了!我已经更新了答案,以反映正确的构造函数。