我写了一个小方法来列出继承的类型,但它不适用于 TreeNode
例如:
假设这个类:
class B { }
class A : B { }
class C :TreeNode { }
然后:
GetInheritedTypes(typeof(A)); //typeof(B)
GetInheritedTypes(typeof(C)); // 0 items
列出它们的方法:
List<Type> GetInheritedTypes(Type baseType)
{
return Assembly.GetAssembly(baseType)
.GetTypes()
.Where(type => type != baseType && type.IsAssignableFrom(baseType))
.ToList();
}
为什么 GetInheritedTypes(typeof(C))
返回 0 个项目而不是 Typeof(TreeNode)
?
最佳答案
Why is GetInheritedTypes(typeof(C)) returning 0 items instead of Typeof(TreeNode)?
因为 TreeNode
与 C
不在同一个程序集中.您的查询是“从与 C 相同的程序集中的所有类型中,给我 C 可分配给的类型”。
不过我怀疑您的实际问题是:
How do I list all the base types of a given type?
您不会搜索程序集中的所有类型并检查哪些类型是可分配的。这就像通过询问你所在城市的每个人“你是 jack 的妈妈吗?”来试图弄清楚你的妈妈是谁。而不是问 jack “谁是你妈妈?”。
像这样会好得多:
public static IEnumerable<Type> BaseTypes(this Type type)
{
if (type == null) throw new ArgumentNullException("type");
Type baseType = type;
while(true)
{
baseType = baseType.BaseType;
if (baseType == null)
break;
yield return baseType;
}
}
评论者提问
what if you want to get all the implemented interfaces?
调用GetInterfaces()
在类型对象上。
(这篇文章的早期版本建议获取接口(interface)的传递闭包;我忘记了 GetInterfaces
已经这样做了。)
How else was my original code broken?
好吧,假设你有一个类型
class D<T> {}
和一个类
class E : D<int> {}
现在你问“给定 E
,列出程序集中的所有类型 X
,这样 E
类型的值可以分配给 X
类型的变量”。嗯,D<T>
在集会中;是D<T>
这样的类型?安号E
可分配给类型为 D<int>
的变量, 不是 D<T>
类型的变量.
“可分配”关系和“继承自”关系有很多重叠,但它们根本不是相同关系,所以不要假装它们是。 p>
关于c# - 获取继承类型列表并不适用于所有类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29104237/