我看到了与我的问题类似的问题:
How to find all the types in an Assembly that Inherit from a Specific Type C#
但是,如果我的类也实现了多个接口怎么办:
class MyClass: MyBaseClass, IMyInterface1, IMyInterface2
我能以某种方式获取MyClass
实现的所有东西的数组,而不仅是一步一步地走吗?
您可以使用类似的方法一劳永逸:
var allInheritance = type.GetInterfaces().Union(new[] { type.BaseType});
对于接口,您可以呼叫Type.GetInterfaces()
如果您对所有基本类型以及接口都感兴趣,则可以使用:
Type.GetInterfaces()
使用方式:
static Type[] BaseTypesAndInterfaces(Type type)
{
var lst = new List<Type>(type.GetInterfaces());
while (type.BaseType != null)
{
lst.Add(type.BaseType);
type = type.BaseType;
}
return lst.ToArray();
}
甚至有可能使其成为通用的
var x = BaseTypesAndInterfaces(typeof(List<MyClass>));
和
static Type[] BaseTypesAndInterfaces<T>()
{
Type type = typeof(T);
var lst = new List<Type>(type.GetInterfaces());
while (type.BaseType != null)
{
lst.Add(type.BaseType);
type = type.BaseType;
}
return lst.ToArray();
}
但是它可能没那么有趣(因为通常您在运行时“发现” var x = BaseTypesAndInterfaces<MyClass>();
,所以您不能轻易地使用泛型方法)]
如果要将基本类型的接口合并到单个数组中,可以执行以下操作:
MyClass
请注意,您的数组将包含所有碱基,包括var t = typeof(MyClass);
var allYourBase = new[] {t.BaseType}.Concat(t.GetInterfaces()).ToArray();
。对于System.Object
,这将不起作用,因为它的基本类型是System.Object
。
这是我使用的扩展方法:
null