jeudi 20 août 2015

Invoke methodinfo inherited from closed generic

 private static void Main(string[] args)
    {
        var messageType = typeof (SampleHandler1);
        var genericType = typeof (IConsume<>).MakeGenericType(messageType);
        var genericArguments = genericType.GetGenericArguments();
        var consumeMethod = genericType.GetMethod("Consume");

        var constructorInfo = genericArguments[0].GetConstructor(Type.EmptyTypes);
        var classObject = constructorInfo.Invoke(new object[] {});

        var argsx = new object[] {new SampleMessage {Name = "sample message"}};

        consumeMethod.Invoke(classObject, argsx);
    }

public interface IConsume<in T> where T : class
{
    void Consume(T message);
}

public class SampleHandler1 : IConsume<SampleMessage>
{
    public SampleHandler1()
    {
        Debugger.Break();
    }

    public void Consume(SampleMessage message)
    {
        Debugger.Break();
        Console.WriteLine("Message consume: " + message.Name);
    }
}


public interface IBaseMessage
{
}

public class SampleMessage : IBaseMessage
{
    public string Name { get; set; }
}

I tried looking here but I cant find specific solution. As MSDN explains

obj Type: System.Object The object on which to invoke the method or constructor. If a method is static, this argument is ignored. If a constructor is static, this argument must be null or an instance of the class that defines the constructor.

classObject is an instance of constructor, right? Why it throws an exception: enter image description here





Aucun commentaire:

Enregistrer un commentaire