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
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
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);
}
}
Well, you can do a visitor-like trick and use the following workaround:
Process(EntityProcessor ep)
in ISomeInterface
A
just as ep.ProcessEntity<A>(this)
(and the same way in B
and C
)ProcessEntity(entity)
in your loop, just call entity.Process(this)
.(the method names are perhaps not cleanest, but you should get the idea)