开发者

Dynamic casting using a generic interface

Is there any way to cast to a dynamic generic interface..

Site s = new Site();
IRepository<Site> obj = (IRepository<s.GetType()>)ServiceLocator.Current.GetInstance(t)

obviously the above won't compile with this cast. Is there anyway to do a dynamic cast of a generic interface. I have tried adding a non generic interface but the system is lo开发者_开发百科oses objects in the Loc container.

Thanks

Phil


Dynamic casting is not easily achievable in C#. You can use 'cast-by-example' - but I would not recommend this - it tends to be confusing.

In you case it's unclear why a 'dynamic' cast is even necessary - if you don't know the type at compile time you can't access any of it's methods or properties. What would such a cast gain you? You may as well just write:

IRespository<Site> obj = 
      (IRepository<ISite>)ServiceLocator.Current.GetInstance(t);

If you're inside a generic method, you can always cast to the generic parameter type:

public void SomeMethod<T>( ) 
    where T : new()
{
    T s = new T();
    IRepository<T> obj = (IRepository<T>)ServiceLocator.Current.GetInstance(t)
    // ...
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜