获取强类型接口方法的名称

Mic*_*hel 4 c# c#-4.0

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

Interface IRequest{

  List<profile> GetProfiles();
  void SetProfile (Profile p);
}
Run Code Online (Sandbox Code Playgroud)

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

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

string s= IRequest.GetProfiles.ToString()
Run Code Online (Sandbox Code Playgroud)

这有可能吗?

编辑:

也许我应该调用它:使用接口,就像它是一个枚举字符串s = IRequest.GetProfiles.ToString()

Abb*_*bas 6

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

//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()
Run Code Online (Sandbox Code Playgroud)

然后:

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

    foreach(MethodInfo method in methods)
    {        
        var methodName = method.Name;
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

你可以用这个

名称(接口.方法)

这很简单