C# Create derived class from System.Type or class name, then add it to collection of the base class

StackOverflow https://stackoverflow.com/questions/22498149

문제

I need to create a derived class object from either its System.Type or its assembly qualified name. I know I can use something like:

Activator.CreateInstance(derivedClassType)

The problem is that after creation, I also need to add this object to a collection of its base class. If I were creating the object normally, I get no errors by doing:

List<BaseClass> myObjects = new List<BaseClass>();
BaseClass obj = new DerivedClass();
myObjects.Add(obj);

However, I can't figure out how to do the same with the Activator instead of normal object creation. I have stored the System.Type and name of the class, and know for certain that the class is derived from the base class. Is there a way to do this?

도움이 되었습니까?

해결책

// 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);

The use of dynamic allows you to NOT use the actual base type in your code and saves you from the hassle of using reflection but you are in danger of violating assumptions such as "I am sure that all these types derive from the same base class so I won't check for that."

다른 팁

The Activator.CreateInstance Method returns only object type. you have to manually typecast it to the base class.

Try the below code,

List<BaseClass> myObjects = new List<BaseClass>();
BaseClass baseClassObj = Activator.CreateInstance(derivedClassType) as BaseClass;
if(baseClassObj != null)
{
   myObjects.Add(baseClassObj);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top