How to use Activator to create an instance of a generic Type and casting it back to that type?

后端 未结 5 633
情歌与酒
情歌与酒 2020-12-01 07:49

I have a generic type Store and use Activator to make an instance of this type. Now how, after using the Activator, can I cast the resulte

5条回答
  •  醉酒成梦
    2020-12-01 08:15

    Most appropriate answer in my opinion would be 'you can't do it in this way'.

    You might try introducing an interface IStorage and try making it covariant or contravariant (have you seen that option?). If it is not an option, for example if you have both input and output generic types used in Storage, then there is no way to implement what you want. The reason is that Storage cannot be safely used as Storage due to this case:

    Storage store = new Storage(); // let's pretend we can do it 
    store.Save(new StorableButNotBeer()); // what will happen here?
    

    The only possible workaround for you as I see is to move casting out from this method and cast the object in the place where you know all the exact types:

    public void object CreateStore(Type istorableType)
    {
        // here is your activator code, but you will have to return an object
    }
    
    var beerStore = (Store)CreateStore(typeof(Beer));
    

提交回复
热议问题