[英]C# Create derived class from System.Type or class name, then add it to collection of the base class
我需要從其System.Type或其程序集限定名稱創建一個派生類對象。 我知道我可以使用類似:
Activator.CreateInstance(derivedClassType)
問題是創建后,我還需要將此對象添加到其基類的集合中。 如果我正常創建對象,則這樣做不會出錯:
List<BaseClass> myObjects = new List<BaseClass>();
BaseClass obj = new DerivedClass();
myObjects.Add(obj);
但是,我無法弄清楚如何使用Activator而不是普通的對象創建方法。 我已經存儲了類的System.Type和名稱,並確定該類是從基類派生的。 有沒有辦法做到這一點?
Activator.CreateInstance方法僅返回對象類型。 您必須手動將其轉換為基類。
試試下面的代碼,
List<BaseClass> myObjects = new List<BaseClass>();
BaseClass baseClassObj = Activator.CreateInstance(derivedClassType) as BaseClass;
if(baseClassObj != null)
{
myObjects.Add(baseClassObj);
}
// create an object of a known type
var someObject = Activator.CreateInstance(derivedClassType);
// get the base class of the known type
var baseType = derivedClassType.BaseType;
// create a type of a generic list
Type openListType = typeof(List<>);
// set the item type of the generic list type to the base stype
Type baseTypeListType = openListType.MakeGenericType(baseType);
// create an instance of the list
dynamic baseTypeList = Activator.CreateInstance(baseTypeListType);
// add
baseTypeList.Add(someObject);
使用dynamic
可以使您不必在代碼中使用實際的基類型,並且可以避免使用反射的麻煩,但是您有違反諸如“我確信所有這些類型都源自同一基類的假設”的危險。我不會檢查的。”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.