如何将对象转换为方法返回类型

4
我希望将args.ReturnValue设置为从调用Create方法创建的TResponse<T>对象的实例。
[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(...) 吗? - KeyNone
@BastiM 谢谢,你的评论帮了我大忙 ;) - msmolcic
1个回答

2

由于Create(...)是静态的,所以您不需要使用Activator类创建实例。只需从ReturnType获取MethodInfo并使用null作为第一个参数调用它:

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> 引入一个非泛型接口。然后,您可以将结果值强制转换为此接口并设置属性。

我根据Basti M的评论自己解决了问题。感谢您的时间,这正是我所做的 :) - msmolcic
由于它是静态方法,我认为您无法拥有通用接口。不是吗? - V. Couvignou
@V.Couvignou:Create(...) 显然不能成为接口的一部分,但可以想象一个类似于 string AdditionalErrorInfo { get; set; } 的属性。 - Stephan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接