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?
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.
来源:https://stackoverflow.com/questions/41179199/cast-genericderived-to-genericbase