I'm developing an application where I the need to invoke a method of a generic class and I don't care about the instances actual type. Something like the following Java code:
public class Item<T>{
private T item;
public doSomething(){...}
}
...
public void processItems(Item<?>[] items){
for(Item<?> item : items)
item.doSomething();
}
At the time I was on a hurry, so I solved my problem by defining a interface with the methods I needed to invoke and made the generic class implement it.
public interface IItem
{
void doSomething();
}
public class Item<T> : IItem {
private T item;
public void doSomething(){...}
}
...
public void processItems(IItem[] items)
{
foreach(IItem item in items)
item.doSomething();
}
This workaround works fine, but I'd like to know what is the correct way to achieve the same behavior.
EDIT:
I forgot to refer that the caller of processItems
doesn't know the actual types. Actually the idea was that the array passed as argument to processItems
could contain intermixed types. Since its not possible to have such an array in .Net, using a non generic base class or interface seems to be the only way.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…