【发布时间】:2015-08-26 17:51:18
【问题描述】:
我想将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 类型,但是当我调用Create 方法时它会抛出RuntimeBinderException。
【问题讨论】:
-
你试过
methodInfo.ReturnType.GetConstructor(...).Invoke(...)吗? -
@BastiM 谢谢,你的评论帮助了我;)
标签: c# dynamic reflection casting postsharp