如何在 C# 中通过反射找到所有未从代码中继承的类型?

问题描述 投票:0回答:1

我有一些从基类继承的类,而其他类则没有继承:

public class SomeDerivedClass : BaseClass

public class FreeFromInheritanceClass
{
}

我想找到

FreeFromInheritanceClass
和其他类似的课程。

我尝试了这段代码,但我想找到

FreeFromInheritanceClass
和其他类似的类。

我尝试了这段代码,但它不起作用:

typeof(Program)
.GetTypes()
.Where(i => i.BaseType == null)

我发现我的

FreeFromInheritanceClass
实际上继承自
System.Object

那么,我怎样才能找到不继承任何东西的类?这不起作用:

typeof(Program)
.GetTypes()
.Where(i => i.BaseType == null)

我发现我的

FreeFromInheritanceClass
实际上继承自
System.Object

那么,我怎样才能找到不继承任何东西的类呢?

c# inheritance reflection
1个回答
0
投票

.NET 中的每个类(和结构)都是

System.Object
,因此请检查基本类型是否为对象:

支持.NET类层次结构中的所有类,并为派生类提供低级服务。这是所有 .NET 类的最终基类;它是类型层次结构的根。

var res = typeof(Program)
    .Assembly
    .GetTypes()
    .Where(i => i.BaseType == typeof(object))
    .ToArray();

如果您还需要用户定义的结构,则添加

i.BaseType == typeof(ValueType)
:

var res = typeof(Program)
    .Assembly
    .GetTypes()
    .Where(i => i.BaseType == typeof(object) || i.BaseType == typeof(ValueType))
    .ToArray();

请注意,输出可能包含一些编译器生成的类,因此您可能需要排除它们(通常它们的名称中包含

<
>
符号)

© www.soinside.com 2019 - 2024. All rights reserved.