mik*_*010 3 c# delegates anonymous-methods func
鉴于以下代码,
public T Execute<T>(Func<T> methodParam)
{
return methodParam ();
}
public void CallMethodsAnonymously<T>()
{
T result = Execute(() => _service.SomeMethod1());
T result1 = Execute(() => _service.SomeMethod2(someParm1));
T result2 = Execute(() => _service.SomeMethod3( someParm1, someParm2));
}
Run Code Online (Sandbox Code Playgroud)
从Execute方法,是否可以检查"methodParam"并提取或确定匿名函数体内的参数数量?例如,是否可以从Execute方法中确定someParam1和someParam2的值?
您可以使用ExpressionAPI 执行此操作:
public static T Execute<T>(Expression<Func<T>> methodParam)
{
var methodCallExpression = methodParam.Body as MethodCallExpression;
var method = methodCallExpression.Method;
var parameters = method.GetParameters();
return methodParam.Compile()();
}
Run Code Online (Sandbox Code Playgroud)
parameters变量将是一个ParameterInfo包含所需信息的对象数组.最后,Compile方法实际上将Expression转换为可执行委托.C#编译器还允许您使用标准lambdas/anonymous方法调用带有委托的方法的常规约定来调用此方法.
编辑:
我还注意到你想要一种方法来获得someParam1和someParam2 的实际值.这是你如何做到这一点:
private static object GetValue(Expression expression)
{
var constantExpression = expression as ConstantExpression;
if (constantExpression != null)
{
return constantExpression.Value;
}
var objectMember = Expression.Convert(expression, typeof(object));
var getterLambda = Expression.Lambda<Func<object>>(objectMember);
var getter = getterLambda.Compile();
return getter();
}
private static object[] GetParameterValues(LambdaExpression expression)
{
var methodCallExpression = expression.Body as MethodCallExpression;
if (methodCallExpression != null)
{
return methodCallExpression.Arguments.Select(GetValue).ToArray();
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
所以现在在你的execute方法中,如果你这样做:
public static T Execute<T>(Expression<Func<T>> methodParam)
{
var methodCallExpression = methodParam.Body as MethodCallExpression;
var method = methodCallExpression.Method;
var parameters = method.GetParameters();
var values = GetParameterValues(methodParam);
return methodParam.Compile()();
}
Run Code Online (Sandbox Code Playgroud)
那么值将是一个对象[],其中包含传入的所有实际值.