简体   繁体   English

通用继承和类型转换

[英]Generic inheritance and type conversion

So I'm attempting to abstract some WPF View/View Models into decoupled reusable objects. 因此,我试图将一些WPF视图/视图模型抽象为解耦的可重用对象。 And now I'm stuck in such a way that I'm not even sure what to try next. 现在,我陷入了困境,甚至不知道下一步该怎么做。 I am hoping someone out there can help get my brain unlocked. 我希望有人可以帮助我解开大脑。

Here is a simplified example and error 这是一个简化的示例和错误

    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();
    }   

I get the following run-time error on the first line in Button_Click method. 我在Button_Click方法的第一行收到以下运行时错误。

System.InvalidCastException was unhandled HResult=-2147467262 Message=Unable to cast object of type 'MyBasicListVm 1[testGenericInheritance.MainWindow+MyBasicListDto]' to type 'IBasicListVm 1[testGenericInheritance.MainWindow+IBasicListDto]'. 未处理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: Source = testGenericInheritance StackTrace:

I have seen a few similar questions/answers, but my brain is just not "Getting it" enough to make needed changes. 我已经看到了一些类似的问题/答案,但是我的大脑还不足以进行必要的更改。

You can make IBasicListVm<T> covariant: 您可以使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