jeudi 1 décembre 2016

Reflection - Call constructor with parameters

I read type from loaded assemblies for example:

var someType = loadedAssemblies
            .Where(a => a != null && a.FullName.StartsWith("MY."))
            .SelectMany(a => a.GetTypes())
            .Distinct()
            .ToArray()[0];

If counstructor has parameters, i can read them:

ParameterInfo[] parameters = classType.GetConstructors()[0].GetParameters();

I would like to call constructor with default parameter values or if parameter is enum, with first enum value. If there is only one parameter and it is enum, it works like this:

object curObject = Activator.CreateInstance(classType, new object[] { parameters[0].ParameterType.GetEnumValues().GetValue(0) });

How can I do this when there are more parameters? I need to create object to read the property:

var propertyInfo = someType.GetProperty("EntityType");
string entityType = propertyInfo.GetValue(curObject, null).ToString();





Aucun commentaire:

Enregistrer un commentaire