Dan*_*nor 1 .net c# reflection
所以,如果我有一个实例
System.Reflection.Assembly
Run Code Online (Sandbox Code Playgroud)
我有以下型号:
class Person {}
class Student : Person {}
class Freshman : Student {}
class Employee : Person {}
class PersonList : ArrayList {}
class StudentList : PersonList {}
Run Code Online (Sandbox Code Playgroud)
如何枚举程序集的类型以仅获取对Person和PersonList类型的引用?
要明确:我不希望在此查找期间显式指定Person或PersonList类型.Person和PersonList只是本例中有问题的程序集中定义的根类型.我正在寻找一种枚举给定程序集的所有根类型的通用方法.
谢谢你的时间:)
怎么样:
var rootTypes = from type in assembly.GetTypes()
where type.IsClass && type.BaseType == typeof(object)
select type;
Run Code Online (Sandbox Code Playgroud)
?或者以非LINQ术语:
foreach (Type type in assembly.GetTypes())
{
if (type.IsClass && type.BaseType == typeof(object))
{
Console.WriteLine(type);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:不,那不会发现PersonList.你需要更清楚"root"的定义.你真的是指"任何类型的基本类型不在同一个程序集中"吗?如果是这样:
var rootTypes = from type in assembly.GetTypes()
where type.IsClass && type.BaseType.Assembly != assembly
select type;
Run Code Online (Sandbox Code Playgroud)