mercredi 22 juillet 2015

C# Reflection: Call constructor with parameters doesn't work.

I having problem calling my constructor with reflection. The parameterless constructor is no problem but when I'm trying to call the once which has parameter I get missingMethodException.

Code:

 if (type != null)
        {
            var constructor = type.GetConstructor(Type.EmptyTypes);
            if (constructor != null)
               return Activator.CreateInstance(type);

            constructor = type.GetConstructors()[0];

            var parameters = constructor.GetParameters();

            var obj = new object[parameters.Length];

            for (var i = 0; i < parameters.Length; i++)
            {
                obj[i] = (object) parameters[i].ParameterType;
            }
            return Activator.CreateInstance(type, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, obj, null);
        }

The parameterless constructor works fine.

 var constructor = type.GetConstructor(Type.EmptyTypes);
            if (constructor != null)
            {
                return Activator.CreateInstance(type);
            }

This part does not:

   constructor = type.GetConstructors()[0];

            var parameters = constructor.GetParameters();

            var obj = new object[parameters.Length];

            for (var i = 0; i < parameters.Length; i++)
            {
                obj[i] = (object) parameters[i].ParameterType;
            }
            return Activator.CreateInstance(type, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, obj, null);
        }

I know that one of the constructors looks like this:

 public class YYY: XXX
{
    public YYY(Guid customerId)
        : base(404, Level.Warn, null, string.Format("{0}",customerId))
    {
    }
}

I also know that the parameterType is not the datatype that the constructor wants:

parameters[i].ParameterType is Guid
false

And.. I know that if I remove obj and put new Guid() it will work:

return Activator.CreateInstance(type, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new Guid(), null);

Question: How can I call the constructor?





Aucun commentaire:

Enregistrer un commentaire