我有一个看起来像这样的界面
public interface IMyService
{
T ServiceProxy<T>(Func<IService, T> request) where T : Response;
}
它的用法如下:
_mysvc.ServiceProxy((p) => p.Execute(new ActivateAccountRequest()));
_mysvc.ServiceProxy((p) => p.Execute(new DeleteAccountRequest()));
即。各种不同的请求类型被发送到包含在Func中的ServiceProxy方法。所有请求都是子类相同的基类
我需要为测试目的创建一个虚假的接口实现。我想根据传递给方法的请求类型做不同的事情
但我无法弄清楚如何识别传递给ServiceProxy方法的请求类型
例如,如果它是ActivateAccountRequest我想做一件事,如果是DeleteAccountRequest我想做另一件事
任何想法?
答案 0 :(得分:1)
将您的界面更改为:
T ServiceProxy<T>(Expression<Func<IService, T>> request) where T : Response;
现在使用此扩展方法获取函数参数:
public static IEnumerable<object> GetFunctionParameters<TInput, TOutput>(this Expression<Func<TInput, TOutput>> expression)
{
var call = expression.Body as MethodCallExpression;
if (call == null)
throw new ArgumentException("Not a method call");
foreach (Expression argument in call.Arguments)
{
LambdaExpression lambda = Expression.Lambda(argument, expression.Parameters);
Delegate d = lambda.Compile();
yield return d.DynamicInvoke(new object[1]);
}
}
然后只需致电request.GetFunctionParameters().First().GetType();