Generic method with a generic interface
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");
精彩评论