强制转换通用通用< Base> [英] Cast Generic<Derived> to Generic<Base>
问题描述
我有一个基本的WPF用户控件,该控件处理派生的用户控件的一些常用功能.在任何派生的UserControl的代码背后,我都调用了一个事件
I have a base WPF UserControl that handles some common functionality for derived UserControls. In the code-behind of any derived UserControl I call an event
private void SomeClick(object sender, RoutedEventArgs e) {
HandleClick(sender);
MyDataGrid.Items.Refresh();
}
在我的基本UserControl中,
In my base UserControl I do
public class BaseUserControl : UserControl {
protected void HandleClick(object sender) {
var vm = (BaseViewModel<Part>)DataContext;
...
}
}
这将引发 InvalidCastException ,因为DataContext
的类型为BaseViewModel
,但具有派生类型,例如BaseViewModel<Wire>
或BaseViewModel<Connector>
.
This throws an InvalidCastException since DataContext
is of type BaseViewModel
but of a derived type like BaseViewModel<Wire>
or BaseViewModel<Connector>
.
我该如何投放?
推荐答案
您不能将Generic<Derived>
强制转换为Generic<Base>
.
试想一下,如果可以的话.您有一个List<Wolf>
并将其强制转换为List<Animal>
.现在,您可以.Add()
一个Sheep
到List<Animal>
.但是等等...现在您的List<Wolf>
包含一个Sheep
.真是一团糟.
Just imagine if you could. You have a List<Wolf>
and cast it to a List<Animal>
. Now you could .Add()
a Sheep
to your List<Animal>
. But wait... now your List<Wolf>
contains a Sheep
. What a mess.
仅当您可以确保投射到的东西为所有可能的形式都是只读的时,这才可行.这是协和逆性为所有关于.不过,它仅适用于接口.
This would only work out if you could make sure that the thing you cast to is read-only in all possible forms. This is was co- and contravariance is all about. It only works for interfaces though.
这篇关于强制转换通用通用< Base>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!