我有一大堆从基类“Port”继承的类
有谁知道如何获取从“Port”继承的所有类的所有公共(public)方法
我知道我必须调用 GetMethods 方法,并且您可以将其调用为一个类型。
我想如果我能以某种方式获得从 Port 继承的所有类的列表,我可以这样做:
(从端口继承的所有类型).SelectMany(x => x.GetMethods());
有人可以帮忙吗?
最佳答案
好的,现在我们知道它们在同一个程序集中,我怀疑您想要:
var methods = from type in typeof(Port).Assembly.GetTypes()
where typeof(Port).IsAssignableFrom(type)
from method in type.GetMethods()
select method;
又名
var methods = typeof(Port).Assembly.GetTypes()
.Where(type => typeof(Port).IsAssignableFrom(type))
.SelectMany(type => type.GetMethods());
请注意,将将Port
本身包含在要获取的类型列表中。
您可能希望使用 BindingFlags.DeclaredOnly
来避免一遍又一遍地获取相同的方法 - 这取决于您之后尝试使用它们做什么。
关于c# - 如何获取从特定类型继承的类的所有方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14761837/