开发者

Generic method with a generic interface

开发者 https://www.devze.com 2023-04-09 08:24 出处:网络
I\'m trying to create a generic method where the type is a generic interface. private void ShowView<T>(string viewName) where T : IView<Screen>

I'm trying to create a generic method where the type is a generic interface.

private void ShowView<T>(string viewName) where T : IView<Screen>
{ 
    IRegion mainRegion = _regionManager.Regions[RegionNames.MainRegion];
    T view = (T)mainRegion.GetView(viewName)开发者_JAVA百科;
    if (view == null)
    {
        view = _container.Resolve<T>();
        mainRegion.Add(view, viewName);
    }
    mainRegion.Activate(view);
    view.LoadData();
    view.ViewModel.IsActive = true;
}

Interface is IView<T> where T : Screen.

So I have ConcreteView : IView<ConcreteViewModel> and ConcreteViewModel : Screen where Screen is the base class. When I try to do ShowView<ConcreteView>("concrete"); I get an UnknownMethod error.

Is it because ConcreteView uses ConcreteViewModel instead of Screen for it's IView implementation? Is there a way to rewrite the method so that it works?


IView<ConcreteViewModel> is not an IView<Screen> without providing variance to the interface

interface IView<out T>
{
}

(The above can be done starting in C# 4.0)

Otherwise, you should be able to write your method signature like below

void ShowView<T, U>(string viewName) where T : IView<U> where U : Screen
{
     // code
}

And invoke it like ShowView<ConcreteView, ConcreteViewModel>("blah");

0

精彩评论

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