开发者

How to call method of instance of generic type when it's type argument is unknown?

开发者 https://www.devze.com 2022-12-15 12:50 出处:网络
This seems like basic problem, but I\'m struggling with it (maybe because of tiredness). E.g. - if i create instance of repository lik开发者_JAVA技巧e this =>

This seems like basic problem, but I'm struggling with it (maybe because of tiredness).

E.g. - if i create instance of repository lik开发者_JAVA技巧e this =>

var repositoryType = typeof(Repository<>).MakeGenericType(entityType);
// repository type==object :(
var repository = ServiceLocator.Current.GetInstance(repositoryType); 

What's the best way to call repository.All() method? Is reflection the only way?


It depends whether Repository<> exposes some non-generic interface (like ITable compared to Table<T> in LINQ-to-SQL). If not, you have to use reflection. If it does, then cast to the non-generic interface:

IRepository repository = (IRepository)ServiceLocator
    .Current.GetInstance(repositoryType); 
IList data = repository.All();

In 4.0, you could also consider dynamic:

dynamic repository = ServiceLocator.Current.GetInstance(repositoryType); 
IList data = repository.All();


In .Net 3.5, it is not possible to do this without reflection or worse.

0

精彩评论

暂无评论...
验证码 换一张
取 消