C# 如何使用反射按名称调用方法

C# 如何使用反射按名称调用方法,c#,reflection,C#,Reflection,嗨,我正在尝试使用C#反射来调用一个方法,该方法被传递一个参数,并返回一个结果。我该怎么做?我尝试过几件事,但都没有成功。我已经习惯了PHP和Python,它们可以在一行中完成,所以这让我很困惑 本质上,这就是不经思考就发出呼吁的方式: response = service.CreateAmbience(request); Type thisType = <your object>.GetType(); MethodInfo theMethod = thisType.GetMeth

嗨,我正在尝试使用C#反射来调用一个方法,该方法被传递一个参数,并返回一个结果。我该怎么做?我尝试过几件事,但都没有成功。我已经习惯了PHP和Python,它们可以在一行中完成,所以这让我很困惑

本质上,这就是不经思考就发出呼吁的方式:

response = service.CreateAmbience(request);
Type thisType = <your object>.GetType();
MethodInfo theMethod = thisType.GetMethod(<The Method Name>); 
theMethod.Invoke(this, <an object [] of parameters or null>); 
请求包含以下对象:

request.UserId = (long)Constants.defaultAmbience["UserId"];
request.Ambience.CountryId = (long[])Constants.defaultAmbience["CountryId"];
request.Ambience.Name.DefaultText = (string)Constants.defaultAmbience["NameDefaultText"];
request.Ambience.Name.LanguageText = GetCultureTextLanguageText((string)Constants.defaultAmbience["NameCulture"], (string)Constants.defaultAmbience["NameText"]);
request.Ambience.Description.DefaultText = (string)Constants.defaultAmbience["DescriptionText"];
request.Ambience.Description.LanguageText = GetCultureTextLanguageText((string)Constants.defaultAmbience["DescriptionCulture"], (string)Constants.defaultAmbience["DescriptionDefaultText"]);
这是我实现反射的函数,其中上述案例的serviceAction为“CreateAmbience”:

publicstaticr-ResponseHelper(T请求,字符串服务操作)
{
ICMSCoreContentService=new ContentServiceRef.CMSCoreContentServiceClient();
R响应=默认值(R);
响应=???
}

大致如下:

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

不过,您可能希望在每个级别添加检查,以确保所讨论的方法实际有效,具有正确的参数类型,并且具有正确的返回类型。这应该足以让您开始学习。

下面是一个使用反射按名称调用对象方法的快速示例:

response = service.CreateAmbience(request);
Type thisType = <your object>.GetType();
MethodInfo theMethod = thisType.GetMethod(<The Method Name>); 
theMethod.Invoke(this, <an object [] of parameters or null>); 
Type thisType=.GetType();
MethodInfo theMethod=thisType.GetMethod();
方法调用(这个,);

如果您在.NET 4上,请使用
动态

dynamic dService = service;
var response = dService.CreateAmbience(request);
您可以使用按名称获取方法的委托:

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);
}
publicstaticr-ResponseHelper(T请求,字符串服务操作)
{
var service=new ContentServiceRef.CMSCoreContentServiceClient();
var func=(func)Delegate.CreateDelegate(typeof(func),
服务
服务行动);
返回func(请求);
}

谢谢Jon,我现在正在尝试解决这个问题,但在“object result=method.Invoke(service,new object[]{request});”行中出现错误-参数计数不匹配。我已经解决了这个问题。您的解决方案可以工作,但反射没有拾取接受1个参数的服务包装器。谢谢你的帮助。