简体   繁体   中英

Using Activator.CreateInstance to create instance of a class and inject Interface to constructor

My goal is to create an instance of a class from it's AssemblyQualifiedName. The problem is that this class requires an interface to be passed in it's constructor and I am having trouble doing this with Activator.CreateInstance.

Thanks in advance for the help.

Once i have the AssemblyQualifiedName of the class I want to instantiate I got it's type using Type.GetType(AQN), used that type to find the constructor and get the required parameters.

I get stuck when calling Activator.CreateInstance and passing the parameters.


var objectType = Type.GetType(AQN);

var constructors = objectType.GetConstructors();

foreach (ConstructorInfo constructor in constructors)
{
    var parameters = constructor.GetParameters();                   
    var instantiatedObj = Activator.CreateInstance(objectType,parameters);
}

Once I do this i get the error "Constructor on Type xxx not found."

There's a Activator.CreateInstance that simply takes the type and the parameters to pass. So you can just say:

ISomeInterface something = null;

var objectType = Type.GetType(AQN);
var instance = Activator.CreateInstance(objectType, something);

if you want to create an instance of the class dynamically then you can do it like this too

        Type type = Type.GetType(AQN);
        PropertyInfo[] properties = type.GetProperties();
        var instance = (BaseClass)Activator.CreateInstance(type);

        for (int i = 0; i < properties.Length; i++)
        {
            PropertyInfo propertyInfo = type.GetProperty(properties[i].Name);
            var propertyVal = Convert.ChangeType(yourpropertyvalue,  
                             properties[i].PropertyType);
            propertyInfo.SetValue(instance, propertyVal);
        }
        return instance;  

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