强制转换泛型<派生>到通用<基础>

发布于 2025-01-09 19:35:07 字数 691 浏览 3 评论 0原文

我有一个基本的 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但属于派生类型,例如 BaseViewModelBaseViewModel

我怎样才能投射它?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁月静好 2025-01-16 19:35:07

您无法将 Generic 转换为 Generic

想象一下如果可以的话。您有一个 List 并将其转换为 List。现在您可以.Add()Sheep添加到您的List中。但是等等...现在您的 List 包含一只 Sheep。真是一团糟。

只有当您能够确保您投射到的内容在所有可能的形式中都是只读的时,这才有效。这是共变和逆变所有关于。但它仅适用于接口。

You cannot cast a Generic<Derived> to a Generic<Base>.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文