繁体   English   中英

通用继承和类型转换

[英]Generic inheritance and type conversion

因此,我试图将一些WPF视图/视图模型抽象为解耦的可重用对象。 现在,我陷入了困境,甚至不知道下一步该怎么做。 我希望有人可以帮助我解开大脑。

这是一个简化的示例和错误

    public interface IBasicListDto{}

    public interface IBasicListVm<T> where T : IBasicListDto
    {
        void DoSomthing();
    }  

    public class BasicListVm<T> : IBasicListVm<T> where T : IBasicListDto
    {
        public void DoSomthing()
        {
            Console.WriteLine("woohoo!!");
        }
    }

   public class MyBasicListDto : IBasicListDto{}

   public class MyBasicListVm<T> : BasicListVm<T> where T : MyBasicListDto {}

   private void Button_Click(object sender, RoutedEventArgs e)
   {
        IBasicListVm<IBasicListDto> vm = (IBasicListVm<IBasicListDto>)new MyBasicListVm<MyBasicListDto>();
        vm.DoSomthing();
    }   

我在Button_Click方法的第一行收到以下运行时错误。

未处理System.InvalidCastException HResult = -2147467262消息=无法将类型为“ MyBasicListVm 1[testGenericInheritance.MainWindow+MyBasicListDto]' to type 'IBasicListVm对象1[testGenericInheritance.MainWindow+MyBasicListDto]' to type 'IBasicListVm 1 [testGenericInheritance.MainWindow + IBasicListDto]”的对象。 Source = testGenericInheritance StackTrace:

我已经看到了一些类似的问题/答案,但是我的大脑还不足以进行必要的更改。

您可以使IBasicListVm<T>协变:

public interface IBasicListVm<out T> where T : IBasicListDto
{
    void DoSomthing();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM