2012-07-17 20 views
0

編寫包含A類異常並將其輸出爲B類型的postsharp方面。這在一些情況下是常見的模式,所以這應該刪除大部分樣板。問題是,如何用激活器創建異常時如何設置內部異常?用激活器,C#,Postsharp設置內部異常

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類型異常沒有爲它定義的構造函數,如何解決這個問題?我必須使用某種反射技巧來寫私人領域嗎?

回答

0

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

事情是這樣的:

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

實際工作版本所需.GetConstructor(新[] {typeof運算(字符串)的typeof(異常)}),但你讓我對正確的軌道,謝謝:) – savpek 2012-07-18 06:42:14

+0

輝煌!我更新了我的答案以反映正確的構造函數。 – 2012-07-18 08:01:43