2015-08-26 62 views
4

我想將args.ReturnValue設置爲從TResponse<T>方法Create創建的對象的實例。如何將對象投射到方法返回類型

[Serializable] 
public sealed class LogError : OnMethodBoundaryAspect 
{ 
    public override void OnException(MethodExecutionArgs args) 
    { 
     // Logging part.. 

     MethodInfo methodInfo = (MethodInfo)args.Method; 

     // I want to replace line below comment to get TResponse<T> object instead of dynamic if possible 
     dynamic returnValue = Activator.CreateInstance(methodInfo.ReturnType); 
     args.ReturnValue = returnValue.Create(CodeMessage.InternalError, MessageType.Error, args.Exception); 

     args.FlowBehavior = FlowBehavior.Return; 
    } 
} 

方法ReturnType永遠是TResponse<T>,但我不知道如何根據方法的返回類型的TResponse<T>創建實例。 TResponse<T>器具方法與此簽名:

.Create(CodeMessage.InternalError, MessageType.Error, args.Exception); 

Create方法是返回與設置參數TResponse<T>對象的靜態方法。

因爲我不知道該怎麼做我想做什麼,我用Activator創建方法的返回類型的實例,並將其存儲到dynamic類型,但它拋出RuntimeBinderException當我打電話Create方法。

+0

您是否嘗試過'methodInfo.ReturnType.GetConstructor(...)。Invoke(...)'? –

+0

@BastiM謝謝,您的評論幫助我; – msmolcic

回答

2

由於Create(...)是靜態的,因此不需要使用Activator類創建實例。剛剛獲得從返回類型一個MethodInfonull並將它作爲第一個參數:

public override void OnException(MethodExecutionArgs args) 
{ 
    // Logging part.. 

    MethodInfo methodInfo = (MethodInfo)args.Method; 

    MethodInfo create = methodInfo.ReturnType.GetMethod(
        "Create", 
        new[] { typeof(CodeMessage), typeof(MessageType), typeof(Exception) }); 
    args.ReturnValue = create.Invoke(null, new object[] { CodeMessage.InternalError, MessageType.Error, args.Exception }); 

    args.FlowBehavior = FlowBehavior.Return; 
} 

MethodInfo.Invoke返回object。由於MethodExecutionArgs.ReturnValue也只是一個object,因此不需要轉換爲實際的TResponse類型。

無論如何,如果你需要在返回值上設置一些額外的屬性,我會爲TResponse<T>引入一個非通用接口。然後,您可以將結果值轉換爲此界面並設置屬性。

+0

我基於Basti M評論自己想出了它。感謝您的時間,這正是我所做的:) – msmolcic

+0

由於它是一個靜態方法,我認爲你不能有一個通用的接口。不是? –

+0

@ V.Couvignou:'Create(...)'顯然可以不是接口的一部分,但想象一個像'string AdditionalErrorInfo {get;組; }' – Stephan