将Generic 转换为Generic

我有一个基本WPF UserControl,它处理派生UserControls的一些常用function。 在任何派生的UserControl的代码隐藏中,我调用一个事件

private void SomeClick(object sender, RoutedEventArgs e) { HandleClick(sender); MyDataGrid.Items.Refresh(); } 

在我的基础UserControl我做

 public class BaseUserControl : UserControl { protected void HandleClick(object sender) { var vm = (BaseViewModel)DataContext; ... } } 

这会引发InvalidCastException,因为DataContext的类型为BaseViewModel但派生类型类似于BaseViewModelBaseViewModel

我怎么能这样做?

您不能将Generic转换为Generic

想想你是否可以。 你有一个List并将其转换为List 。 现在你可以。添加.Add() Sheep到你的List 。 但是等等……现在你的List包含一只Sheep 。 真是一团糟。

只有当你能确保你所投射的东西是以所有可能forms的只读时才能解决这个问题。 这是共同的,而且是相反的 。 它只适用于接口。