lundi 10 février 2020

c# reflectin: calling method with generic type and generic parameter for given instance of class

I need to call generic method with generic parameter using reflection, where generic type is supplied as parameter within string. There are some examples online for generics and reflection, but I still cannot get this to work.

Without reflection:

        string typeName = "EventType"; // as param1 -> type name
        string content = ""; //as param2 -> some json cotnent

        IMyBus bus = new MyBus();
        switch (typeName)
        {
            case "EventType":
                IEventType content = Deserialize<IEventType>(content);
                bus.Publish<IEventType>(content);
                break;
            case "EventType2":
                IEventType2 content2 = Deserialize<IEventType2>(content);
                bus.Publish<IEventType2>(content2);
                break;
        }

Instead I would like to rewrite it using reflection to supply more EventTypes without rewriting this particular code.

Below are my test classes:

 public interface IMyBus **//TWO METHODS HERE, WE NEED TO CALL FIRST ONE!**
 {
     void Publish<T>(T message, CancellationToken cancellationToken = default(CancellationToken)) where T : class; //THIS SHOULD BE CALLED
     void Publish<T>(T message, int i, CancellationToken cancellationToken = default(CancellationToken)) where T : class;
  }

  // Interface implementation
  public class MyBus : IMyBus
  {
      public void Publish<T>(T message, CancellationToken cancellationToken = default(CancellationToken)) where T : class
      {  ... }
      public void Publish<T>(T message, int i, CancellationToken cancellationToken = default(CancellationToken)) where T : class
      {  ... }
    }

    public interface IEventType { int forTest { get; set; } }

    public class EventType : IEventType { public int forTest { get; set; } }

    public interface IEventType2 { int forTest2 { get; set; } }

    public class EventType2 : IEventType2 { public int forTest2 { get; set; } }

And here is what I already tried:

 IMyBus bus = new MyBus();
 EventType content = new EventType() { forTest = 1 };
 var eventTypeName = $"ConsoleApp.EventType";
 var iEventTypeName = $"ConsoleApp.IEventType";

 Type intEvType = Type.GetType(iEventTypeName);
 Type evType = Type.GetType(eventTypeName);

 MethodInfo openGenericMethod = typeof(IMyBus).GetMethod("Publish", 2, new Type[] { intEvType, typeof(CancellationToken) });
 MethodInfo closedGenericMethod = openGenericMethod.MakeGenericMethod(evType);
 object o2 = closedGenericMethod.Invoke(bus, new object[] { content });

But this is wrong. openGenericMethod is always null.





Aucun commentaire:

Enregistrer un commentaire