Calling a generic method with the correct derived type

后端 未结 3 901
旧时难觅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

提交回复
热议问题