Calling a generic method with the correct derived type

后端 未结 3 902
旧时难觅i
旧时难觅i 2021-02-08 20:28

I have the following scenario:

I have three classes, let\'s call them A, B and C. All they have in common is that they inherit fro

相关标签:
3条回答
  • 2021-02-08 20:48

    You could use reflection to get the generic method definition and then call it, eg:

    var method = typeof(ClassContainingProcessEntity)
        .GetMethod(ProcessEntity)
        .MakeGenericMethod(entity.GetType);
    method.Invoke(this, entity);
    

    You could cache the method by type, and you could compile it at runtime using some kind of delegate factory if performance is critical.

    Alternatively you could use the Visitor pattern

    0 讨论(0)
  • 2021-02-08 20:49

    You can apply dynamic keyword when passing entity to ProcessEntity. In this case actual type of entity will be determined at runtime.

    public void MyMethod(List<ISomeInterface> entityList)
    {
      foreach(var entity in entityList)
      {
        dynamic obj = entity;
        ProcessEntity(obj);
      }
    }
    
    0 讨论(0)
  • 2021-02-08 20:54

    Well, you can do a visitor-like trick and use the following workaround:

    1. Define a method Process(EntityProcessor ep) in ISomeInterface
    2. Implement it in A just as ep.ProcessEntity<A>(this) (and the same way in B and C)
    3. Instead of ProcessEntity(entity) in your loop, just call entity.Process(this).

    (the method names are perhaps not cleanest, but you should get the idea)

    0 讨论(0)
提交回复
热议问题