强制转换泛型<派生>到通用<基础>基础>派生>
我有一个基本的 WPF UserControl,它处理派生 UserControl 的一些常见功能。在任何派生的 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<Part>)DataContext;
...
}
}
这会抛出 InvalidCastException,因为 DataContext
的类型为 BaseViewModel
但属于派生类型,例如 BaseViewModel
或 BaseViewModel
。
我怎样才能投射它?
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();
}
In my base UserControl I do
public class BaseUserControl : UserControl {
protected void HandleClick(object sender) {
var vm = (BaseViewModel<Part>)DataContext;
...
}
}
This throws an InvalidCastException since DataContext
is of type BaseViewModel
but of a derived type like BaseViewModel<Wire>
or BaseViewModel<Connector>
.
How can I cast that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法将
Generic
转换为Generic
。想象一下如果可以的话。您有一个
List
并将其转换为List
。现在您可以.Add()
将Sheep
添加到您的List
中。但是等等...现在您的List
包含一只Sheep
。真是一团糟。只有当您能够确保您投射到的内容在所有可能的形式中都是只读的时,这才有效。这是共变和逆变所有关于。但它仅适用于接口。
You cannot cast a
Generic<Derived>
to aGeneric<Base>
.Just imagine if you could. You have a
List<Wolf>
and cast it to aList<Animal>
. Now you could.Add()
aSheep
to yourList<Animal>
. But wait... now yourList<Wolf>
contains aSheep
. 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.