문제

In a namespace I have an arbitrary number of classes fulfilling an interface IModel. Given the name of a class as a string, I want to instantiate that class and store the resulting object in a variable of type IModel.

As I have no experience in reflection, I did not figure out how to do it.

도움이 되었습니까?

해결책

You don't need reflection here - use Activator

IModel model = (IModel)Activator.CreateInstance(Type.GetType(typeName));

다른 팁

You could have a look at Activator.CreateInstance.

There are many ways to do this. I do the following:

Type t = Type.GetType("<name of class>");
IModel m = (IModel)Activator.CreateInstance(t); // assuming constructor has no parameters
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top