本文介绍了Cast Generic<Derived>到 Generic <Base >的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的 WPF UserControl,用于处理派生的 UserControl 的一些常见功能.在任何派生 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 的派生类型> 或 BaseViewModel.

This throws an InvalidCastException since DataContext is of type BaseViewModel but of a derived type like BaseViewModel<Wire> or BaseViewModel<Connector>.

我该如何投射?

推荐答案

您不能将 Generic 转换为 Generic.

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

想象一下,如果可以的话.您有一个 List 并将其转换为 List.现在您可以将 .Add() 一个 Sheep 添加到您的 List 中.但是等等......现在你的List 包含一个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.

这篇关于Cast Generic&lt;Derived&gt;到 Generic &lt;Base &gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 03:16