使用.net反射来查找共同的祖先类
我有一个程序集,其中包含具有共同祖先类(在程序集中定义)的类型。在大多数情况下,共同祖先不是该类的直接基类型。
我需要能够从所有类型中筛选出由于各种原因,我无法实例化这些类型(它们通常没有共同的构造函数签名),因此我必须从 myAssembly.GetTypes()< 开始。 /code> 并检查属性 我必须使用类,而不是类的实例,
如何检查该集合中的每个类型以确定它是否继承自所需的共同祖先?
换句话说, 现在的技巧是从程序集中实例化一个作为祖先类型的类型对象,例如,
Type ancestor = assy.getType("myAncestorClassName", true, true);
Type[] interestingClasses = assy.GetTYypes().Where(t => t.IsSubclassOf(ancestor));
但是这不起作用:
Type[] interestingClasses = assy.GetTYypes().Where(t => t.IsSubclassOf(typeof(AncestorClass)));
因为我认为祖先类型是在另一个程序集中定义的,而不是在。 主要集会......感谢所有做出贡献的人。
很久很久以后的 对此的答案。一路上我被转移到其他事情上,但我现在有了一个巧妙的解决方案(并且学到了新的东西)。
I have an assembly containing types that have a common ancestor class (defined within the assembly. The common ancestor is in most cases not the class's immediate base type.
I need to be able to filter out, from all the types in this assembly, those with this common ancestor. For various reasons I can't instantiate the types (they do not as a rule have a common constructor signature) so I have to start with myAssembly.GetTypes()
and examine the properties of the types themselves. In other words I have to work with classes, not instances of the classes.
How do I examine each Type in this collection to find if it inherits from the desired common ancestor or not?
Later: no worries, I have it now. The trick is to instantiate a type object that is the ancestor type from the assembly, eg
Type ancestor = assy.getType("myAncestorClassName", true, true);
Type[] interestingClasses = assy.GetTYypes().Where(t => t.IsSubclassOf(ancestor));
However this will not work:
Type[] interestingClasses = assy.GetTYypes().Where(t => t.IsSubclassOf(typeof(AncestorClass)));
because, I think, the ancestor type is defined in the other assembly and not in the main assembly.
Much, much later....Thanks to everyone who contributed answers to this. I was diverted to something else along the way, but I now have a neat solution (and have learned something new).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于集合中的每种类型,您可以使用 Type.IsAssignableFrom。
例如:
这应该获取程序集中不是从
CommonAncestor
派生的所有类型。For each type in your collection, you can see if they derive from this ancestor by using Type.IsAssignableFrom.
For example:
This should get all types in the assembly which aren't derived from
CommonAncestor
.使用 Type.IsAssignableFrom查明一种类型是否可以从另一种类型的实例分配。
Use Type.IsAssignableFrom to find out if one type is assignable from an instance of another type.
假设您使用 C#
Assuming you're using C#
查看此代码片段:
这将获取当前程序集中从
object
派生的所有类型。当然,将其替换为您自己的共同祖先类型。Type.IsAssignableFrom()
方法检查您是否可以执行以下操作:没有错误。
Check out this snippet:
This will fetch all types in the current assembly that are descended from
object
. Naturally, replace it with your own common ancestor type.The
Type.IsAssignableFrom()
method checks if you can do something like:without errors.