簡體   English   中英

使用激活器C#,Postsharp設置內部異常

[英]Setting inner exception with activator, C#, Postsharp

編寫包裝A類型異常並將其輸出為B類型的postharsh方面。 在某些情況下,這是常見的模式,因此應該刪除很多樣板。 問題是,使用激活器創建異常時如何設置內部異常?

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類型異常沒有為其定義構造函數的錯誤,如何解決呢? 我是否必須使用某種反射技巧來寫私有字段?

使用Type.GetConstructor(Type [])獲得適當的Exception構造函數。 http://msdn.microsoft.com/zh-CN/library/h93ya84h.aspx

像這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM