[英]Convert system.Type to user defined type
我试图让所有类都继承基类。
public void GetClassNames()
{
List<BaseClass> data = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(assembly => assembly.GetTypes())
.Where(type => type != null &&
type.IsSubclassOf(typeof(BaseClass))).ToList();
}
但是,上面的代码将引发错误。
“无法将类型System.Collections.Generic.List<System.Type>' to
隐式转换System.Collections.Generic.List<System.Type>' to
System.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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.