通过反射确定派生类 [英] Determining derived classes through reflection
问题描述
我想处理从类A派生的类的方法。类A和派生类驻留在不同的程序集中。我使用反射从派生程序集中获取所有System.Type并迭代它们的方法。
I want to process the Methods of classes derived from class A. Class A and the derived classes reside in different assemblies. I use reflection to get all System.Type's from the derived assembly and iterate through their methods.
Assembly A: class Template {...}
Assembly B: class X: A.Template {...}
Assembly B: class Y: A.Template {...}
Assembly B: class Z: A.Template {...}
当我尝试迭代类 B
中的> X ,它包括类 A
的所有方法。我想要实现的只是遍历派生类中存在的那些方法。
When I try to iterate the methods of class X
in assembly B
, it includes all methods of class A
. What I want to achieve is to iterate through only those methods that exist in derived classes.
我不认为在不同的程序集中是重要的,但即使我尝试根据程序集过滤方法的声明类型,它不起作用。
I don't think that being in different assemblies matters at all but even when I try to filter the method's declaring type based on the assembly, it does not work.
我尝试使用 MethodInfo的各种属性
对象但未能过滤掉它。我确信我错过了一些愚蠢的检查,但一直在努力解决这个问题。
I have tried using various properties of the MethodInfo
object but have not been able to filter this out. I am sure I'm missing some silly check but have been struggling with this for long enough.
任何建议都会受到赞赏。
Any advice would be appreciated.
推荐答案
您可以使用它来获取程序集中的所有派生类型:
You can use this to get all derived types in an assembly:
Assembly b = Assembly.LoadFrom(@"c:\B.dll");
var derivedTypes = b.GetTypes().Where(t => typeof(Template).IsAssignableFrom(t));
这是为了找到在该类型上定义的任何方法:
And this to find any methods defined on that type:
Type derived = ...
var methods = derived.GetMethods(BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.DeclaredOnly);
或者这个:
var methods = derived.GetMethods().Where(m => m.DeclaringType == derived);
但是,如果要查找在 Template <的任何子类上定义的方法/ code>(例如
X
的子类),使用:
However, if you want to find methods defined on any subclass of Template
(e.g. a subclass of X
), use this:
Type templateType = typeof(Template);
Type derived = ...
var methods = derived.GetMethods()
.Where(m => templateType.IsAssignableFrom(m.DeclaringType) &&
templateType != m.DeclaringType);
这篇关于通过反射确定派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!