将 system.Type 转换为用户定义的类型

Convert system.Type to user defined type

我正在尝试让所有 classes 继承一个基础 class。

  public void GetClassNames()
  {

     List<BaseClass> data = AppDomain.CurrentDomain.GetAssemblies()
                           .SelectMany(assembly => assembly.GetTypes())
                           .Where(type => type != null && 
                           type.IsSubclassOf(typeof(BaseClass))).ToList();
  }

但是,上面的代码会抛出错误。
"Cannot implicitly convert type System.Collections.Generic.List<System.Type>' toSystem.Collections.Generic.List"

请问如何将它转换为 BaseClass 类型?

您正在选择 BaseClass 的子 类 的所有程序集的所有类型。所以你得到所有类型但不是这些类型的实例。

你真正想要的是什么?方法名称是 GetClassNames,所以也许你想要:

public IEnumnerable<string> GetClassNames()
{
    List<string> baseClassNames = AppDomain.CurrentDomain.GetAssemblies()
       .SelectMany(assembly => assembly.GetTypes())
       .Where(type => type?.IsSubclassOf(typeof(BaseClass)) == true)
       .Select(type => type.FullName)
       .ToList();
    return baseClassNames;
}

如果您希望所有程序集中的所有类型都派生自您的 BaseClass:

public IEnumnerable<Type> GetBaseClassSubTypesInCurrrentAssenblies()
{
    List<Type> baseClassTypes = AppDomain.CurrentDomain.GetAssemblies()
       .SelectMany(assembly => assembly.GetTypes())
       .Where(type => type?.IsSubclassOf(typeof(BaseClass)) == true)
       .ToList();
    return baseClassTypes;
}