所以我试图将一些 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+IBasicListDto]”的对象。来源=testGenericInheritance StackTrace:
我见过一些类似的问题/答案,但我的大脑还没有“明白”到足以做出必要的改变。