获取强类型接口方法的名称 [英] Get the name(s) of interface methods strong typed

查看:30
本文介绍了获取强类型接口方法的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这个例子的界面:

i have an interface like this example:

Interface IRequest{

  List<profile> GetProfiles();
  void SetProfile (Profile p);
}

现在,在某些日志组件中,我无权访问实现接口的对象,但我想使用接口中方法的名称.我当然可以将它们键入为字符串(将方法名称复制到字符串中),但我想使用强类型的它们,这样我就不必使方法名称和字符串保持同步.

Now, in some logging component, i don't have access to the object implementing the interface, but i want to use the names of the methods in the interface. i can of course type them as a string (copy the method name in a string), but i want to use them strong typed so i don't have to keep the method names and string in sync.

在伪代码中,我会这样做:

In pseudo code, i would do this:

string s= IRequest.GetProfiles.ToString()

这有可能吗?

也许我应该这样称呼它:像使用 Enum 一样使用接口字符串 s= IRequest.GetProfiles.ToString()

Maybe i should call it: use the interface like it's an Enum string s= IRequest.GetProfiles.ToString()

推荐答案

您可以通过两种方式实现:

You can achieve this in two ways:

//If you CAN access the instance
var instance = new YourClass(); //instance of class implementing the interface
var interfaces = instance.GetType().GetInterfaces();

//Otherwise get the type of the class
var classType = typeof(YourClass); //Get Type of the class implementing the interface
var interfaces = classType.GetInterfaces()

然后:

foreach(Type iface in interfaces)
{
    var methods = iface.GetMethods();

    foreach(MethodInfo method in methods)
    {        
        var methodName = method.Name;
    }
}

这篇关于获取强类型接口方法的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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