简体   繁体   中英

How to instantiate an object of a type passed by parameter, that needs to implement a certain interface?

Lets say I have an interface called IMyInterface, and a class called MyClass that implements IMyInterface

In another class I have a method that has a type as parameter and this type must implement IMyInterface to be valid. eg MyClass would be a valid argument. Then in the method I would instantiate an object of the type passed by parameter.

How would I achieve this? If not possible, what solution would have a similar effect?

There are two parts of the answer. First you should validate type by Type.IsAssignableFrom :

var implementInterface = (typeof(IMyInterface)).IsAssignableFrom(type);
if(!implementInterface)
    // return null, throw an exception or handle this scenario in your own way

Next you can instantiate an object. here are several ways you can create an object of a certain type on the fly, one is use Activator.CreateInstance :

// create an object of the type
var obj = (IMyInterface)Activator.CreateInstance(type);

And you'll get an instance of MyClass in obj.

Another way is to use reflection:

// get public constructors
var ctors = type.GetConstructors(BindingFlags.Public);

// invoke the first public constructor with no parameters.
var obj = ctors[0].Invoke(new object[] { });

And from one of ConstructorInfo returned, you can "Invoke()" it with arguments and get back an instance of the class as if you've used a "new" operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM