开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜