I have a generic type Store<T>
and use Activator
to make an instance of this type. Now how, after using the Activator, can I cast the resulted object of type object
back to the instantiated type? I know the type that I used to instantiate the generic. Please see the following code:
class Store<T> where T : IStorable
{}
class Beer : IStorable
{}
class BeerStore : Store<Beer>
{}
Type storeType = someObjectThatImplementsIStorable.GetType();
Type classType = typeof(Store<>);
Type[] typeParams = new Type[] { storeType };
Type constructedType = classType.MakeGenericType(typeParams);
object x = Activator.CreateInstance(constructedType, new object[] { someParameter });
What I would like to do is something like this:
var store = (Store<typeof(objectThatImplementsIStorable)>)x;
but that doesn't work for obvious reasons. As an alternative I tried:
var store = (Store<IStorable>)x;
which could possibly work in my opinion, but gives an InvalidCastException
.
How do I get access again to the Store<T>
methods that I know are in the object x
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…