如何使用反射按名称调用方法 [英] How to use reflection to call method by name

查看:18
本文介绍了如何使用反射按名称调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试使用 C# 反射来调用传递参数并返回结果的方法.我怎样才能做到这一点?我已经尝试了几件事,但没有成功.我已经习惯了 PHP 和 Python,它们可以在一行中完成,所以这让我很困惑.

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 with no success. I'm used to PHP and Python where this can be done on a single line so this is very confusing to me.

本质上这就是没有反射的调用方式:

In essence this is how the call would be made without reflection:

response = service.CreateAmbience(request);

请求有这些对象:

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":

This is my function to implement the reflection where serviceAction for the case above would be "CreateAmbience":

public static R ResponseHelper<T,R>(T request, String serviceAction)
{
    ICMSCoreContentService service = new ContentServiceRef.CMSCoreContentServiceClient();
    R response = default(R);
    response = ???
}

推荐答案

大致如下:

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.

这篇关于如何使用反射按名称调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆