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

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

问题描述

我有一个这样的例子的接口:

i have an interface like this example:

Interface IRequest{

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

现在,在一些记录组件,我没有访问对象实现接口,但我想使用的接口中的方法的名称。当然,
I可以输入他们作为一个字符串(字符串中的复制方法名),但我想利用它们强大的类型,所以我没有保留的方法名称和字符串同步。

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()

在某种程度上这是可能的吗?

Is this in a way possible?

编辑:

也许我应该把它叫做:使用该接口就像是一个枚举
字符串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天全站免登陆