繁体   English   中英

如何从函数表达式中获取方法名称和参数?

[英]How can I get the method name and parameters from a function expression?

例:

由于本示例范围之外的原因,我被迫使用此方法:

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);            
}

但是,我更喜欢这样的事情:

UserRepository repository = new UserRepository();
User user = GetUserById<User, UserRepository>(repository, m => m.GetUserById(2));

包装程序可以完成此任务。 我开始建造一个,但是被卡住了。 这就是我所拥有的:

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);
}

请记住,我被迫使用InvokeMethod方法。 我不能简单地调用Func。

这取决于参数是否为文字,捕获的变量等,以及它们是否为refout等,因此变得很复杂。您可能要看一下protobuf-net.Extensions中的实现, 此处提供了所有代码-特别是ResolveMethod方法。

MethodInfo很简单-只需将Body .Method.NameMethodCallExpression并获取.Method.Name但是对于它递归调用Evaluate的参数-这允许像SomeMethod(123, x, y.Foo.Bar)这样的表达式起作用,其中123是文字, x是一个捕获的变量,并且y.Foo.Bar东西在捕获的变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM