How to use reflection to call method by name

后端 未结 4 1380
太阳男子
太阳男子 2020-11-28 13:46

Hi I am trying to use C# reflection to call a method that is passed a parameter and in return passes back a result. How can I do that? I\'ve tried a couple of things but wit

相关标签:
4条回答
  • 2020-11-28 13:54

    You can use Delegate.CreateDelegate to obtain a delegate to the method by name:

    public static R ResponseHelper<T,R>(T request, string serviceAction)
    {
        var service = new ContentServiceRef.CMSCoreContentServiceClient();
    
        var func = (Func<T,R>)Delegate.CreateDelegate(typeof(Func<T,R>),
                                                      service,
                                                      serviceAction);
    
        return func(request);
    }
    
    0 讨论(0)
  • 2020-11-28 13:55

    Here's a quick example of calling an object method by name using reflection:

    Type thisType = <your object>.GetType();
    MethodInfo theMethod = thisType.GetMethod(<The Method Name>); 
    theMethod.Invoke(this, <an object [] of parameters or null>); 
    
    0 讨论(0)
  • 2020-11-28 13:55

    If you're on .NET 4, use dynamic:

    dynamic dService = service;
    var response = dService.CreateAmbience(request);
    
    0 讨论(0)
  • 2020-11-28 14:17

    Something along the lines of:

    MethodInfo method = service.GetType().GetMethod(serviceAction);
    object result = method.Invoke(service, new object[] { request });
    return (R) result;
    

    You may well want to add checks at each level though, to make sure the method in question is actually valid, that it has the right parameter types, and that it's got the right return type. This should be enough to get you started though.

    0 讨论(0)
提交回复
热议问题