[英]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.