我想將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
方法。
您是否嘗試過'methodInfo.ReturnType.GetConstructor(...)。Invoke(...)'? –
@BastiM謝謝,您的評論幫助我; – msmolcic