如何获取装配中的所有基本类型?

时间:2022-11-08 19:02:21

So if I have an instance of

所以,如果我有一个实例

System.Reflection.Assembly 

and I have the following model:

我有以下型号:

class Person {}
class Student : Person {}
class Freshman : Student {}
class Employee : Person {}
class PersonList : ArrayList {}
class StudentList : PersonList {}

How can I enumerate the assembly's types to get a reference to only the Person and PersonList types?

如何枚举程序集的类型以仅获取对Person和PersonList类型的引用?

To be clear: I don't want to ever explicitly specify the Person or PersonList type during this lookup. Person and PersonList are just the root type defined in the assembly in question for this example. I'm shooting for a general way to enumerate all the root types for a given assembly.

要明确:我不希望在此查找期间明确指定Person或PersonList类型。 Person和PersonList只是本例中有问题的程序集中定义的根类型。我正在寻找一种枚举给定程序集的所有根类型的通用方法。

Thank for your time :)

谢谢你的时间:)

1 个解决方案

#1


How about:

var rootTypes = from type in assembly.GetTypes()
                where type.IsClass && type.BaseType == typeof(object)
                select type;

? Or in non-LINQ terms:

?或者以非LINQ术语:

foreach (Type type in assembly.GetTypes())
{
    if (type.IsClass && type.BaseType == typeof(object))
    {
        Console.WriteLine(type);
    }
}

EDIT: No, that wouldn't spot PersonList. You'll need to be clearer about the definition of "root". Do you actually mean "any type whose base type isn't in the same assembly"? If so:

编辑:不,那不会发现PersonList。你需要更清楚“root”的定义。你真的是指“基本类型不在同一个程序集中的任何类型”吗?如果是这样:

var rootTypes = from type in assembly.GetTypes()
                where type.IsClass && type.BaseType.Assembly != assembly
                select type;

#1


How about:

var rootTypes = from type in assembly.GetTypes()
                where type.IsClass && type.BaseType == typeof(object)
                select type;

? Or in non-LINQ terms:

?或者以非LINQ术语:

foreach (Type type in assembly.GetTypes())
{
    if (type.IsClass && type.BaseType == typeof(object))
    {
        Console.WriteLine(type);
    }
}

EDIT: No, that wouldn't spot PersonList. You'll need to be clearer about the definition of "root". Do you actually mean "any type whose base type isn't in the same assembly"? If so:

编辑:不,那不会发现PersonList。你需要更清楚“root”的定义。你真的是指“基本类型不在同一个程序集中的任何类型”吗?如果是这样:

var rootTypes = from type in assembly.GetTypes()
                where type.IsClass && type.BaseType.Assembly != assembly
                select type;