Since the actual type T
is available to you only through reflection, you would need to access methods of Store<T>
through reflection as well:
Type constructedType = classType.MakeGenericType(typeParams);
object x = Activator.CreateInstance(constructedType, new object[] { someParameter });
var method = constructedType.GetMethod("MyMethodTakingT");
var res = method.Invoke(x, new object[] {someObjectThatImplementsStorable});
EDIT You could also define an additional IStore
interface that does not use generics, and uses IStorable
instead:
interface IStore {
int CountItems(IStorable item);
}
class Store<T> : IStore where T : IStorable {
int CountItems(IStorable item) {
return count;
}
}
Your Store<T>
would remain generic, but you would get access to its CountItems
by casting to IStore
:
var x = (IStore)Activator.CreateInstance(constructedType, new object[] { someParameter });
var count = x.CountItems((IStorable)someObjectThatImplementsStorable);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…