[英]How can I get the method name and parameters from a function expression?
Example: 例:
For reasons outside the scope of this example, I am forced to use this: 由于本示例范围之外的原因,我被迫使用此方法:
UserRepository repository = new UserRepository();
User user = (User)InvokeMethod(repository, "GetUserById", new object[]{2});
private object InvokeMethod(object source, string methodName, object[] parameters)
{
Type sourceType = source.GetType();
MethodInfo methodInfo = sourceType.GetMethod(methodName);
return methodInfo.Invoke(source, parameters);
}
However, I would much prefer something like this: 但是,我更喜欢这样的事情:
UserRepository repository = new UserRepository();
User user = GetUserById<User, UserRepository>(repository, m => m.GetUserById(2));
A wrapper could accomplish this. 包装程序可以完成此任务。 I started to build one, but got stuck. 我开始建造一个,但是被卡住了。 This is what I have: 这就是我所拥有的:
public TUser GetUserById<TUser, TUserRepository>(TUserRepository repository, Expression<Func<TUserRepository, TUser>> repositoryFunc)
where TUser : User
where TUserRepoistory : UserRepository
{
// How do I use the Expression to setup the next two statements?
string methodName = ""; // should be "GetUserId"
object[] params = null; // should be "object[] { 2 }"
TUser user = (TUser)InvokeMethod(repository, methodName, parameters);
}
Keep in mind I am forced to use the InvokeMethod method. 请记住,我被迫使用InvokeMethod方法。 I cannot simply invoke the Func. 我不能简单地调用Func。
This gets complex depending on whether the arguments are literals, captured variables, etc - and whether they are ref
, out
, etc. You might want to look at the implementation in protobuf-net.Extensions, here , which has code to all of this - in particular the ResolveMethod
method. 这取决于参数是否为文字,捕获的变量等,以及它们是否为ref
, out
等,因此变得很复杂。您可能要看一下protobuf-net.Extensions中的实现, 此处提供了所有代码-特别是ResolveMethod
方法。
The MethodInfo
is simple - just cast Body
to MethodCallExpression
and obtain the .Method.Name
- but for the parameters it recursively calls into Evaluate
- this allows expressions like SomeMethod(123, x, y.Foo.Bar)
to work, where 123
is a literal, x
is a captured variable, and y.Foo.Bar
is something hanging off a captured variable. MethodInfo
很简单-只需将Body
.Method.Name
为MethodCallExpression
并获取.Method.Name
但是对于它递归调用Evaluate
的参数-这允许像SomeMethod(123, x, y.Foo.Bar)
这样的表达式起作用,其中123
是文字, x
是一个捕获的变量,并且y.Foo.Bar
东西挂在捕获的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.