How to get a list of Interface members

2020-04-07 04:40发布

Is there a way to get a list of interface members? I know about System.Reflection.MemberInfo, but it includes everything in an object, not just a certain interface.

Here is the program, I'm not sure how to get you the interface as I didn't write it, but it is part of the Ascom Standard (http://ascom-standards.org).

public static void Test1()
{
    Console.WriteLine("mark1"); // this shows up...
    var type = typeof(Ascom.Interface.ITelescope);
    var members = type.GetMembers();
    Console.WriteLine(members.Count); // gives 0
    foreach (var member in members)
    {
        Console.WriteLine(member.Name); //nothing from here
    }
    Console.WriteLine("mark4"); // ...as well as this
}

标签: c#
5条回答
聊天终结者
2楼-- · 2020-04-07 04:49

You just need to ask for the members for the interface type:

var type = typeof(IConvertible);
var members = type.GetMembers();

foreach (var member in members)
{
    Console.WriteLine(member.Name); // ToInt32 etc
}
查看更多
不美不萌又怎样
3楼-- · 2020-04-07 04:51

If it is a COM interface, then you should disable "Embed Interop Types", otherwise it will only insert used members in the assembly. I guess you don't use any methods/properties from that interface in the assembly, that's why they never get inserted, so you can list them with reflection. (Thx OWO)

查看更多
做自己的国王
4楼-- · 2020-04-07 04:53

From MSDN:

typeof(IList).GetMembers()

Gets the members (properties, methods, fields, events, and so on) of the current Type.

查看更多
放荡不羁爱自由
5楼-- · 2020-04-07 04:59
var t = typeof(IMyInterface);
foreach( var m in t.GetMethods() ){
    Debug.WriteLine(m.Name);
}
查看更多
够拽才男人
6楼-- · 2020-04-07 05:11

To get a list of members of some interface, you can just do that: list members of that interface, as others pointed out:

var members = interfaceType.GetMembers();

But if you want to know what members of certain type implement that interface, you can use GetInterfaceMap() and examine the TargetMethods field:

var members = type.GetInterfaceMap(interfaceType).TargetMethods;
查看更多
登录 后发表回答