在双类型泛型中对一种类型的 C# 向上转换不起作用

本文关键字:类型 一种 不起作用 转换 泛型 | 更新日期: 2023-09-27 18:33:12

我准备了一个示例应用程序,用于解决我在大型 WPF 应用程序中遇到的问题。

我遇到的问题是将第二种类型的 TreeColumn 实例obsTreeColumn转换为Collection。正如你所看到的,当我只用一种类型执行此操作时,向上投射工作正常。该方法DoSomethingWithColumn需要能够将任何类型的集合作为参数collection的第二个泛型类型。

public class TreeColumn<T, TValue>  where TValue : Collection<T> {
    // A lot happens in here...
}
public class Data {
    public int Id { get; set; }
    public int Code { get; set; }
    // And much more...
}
class Program {
    static void Main(string[] args) {
        var expander = new TreeExpander<Data>();
        var obsTreeColumn = new TreeColumn<Data, ObservableCollection<Data>>();
        var colTreeColumn = new TreeColumn<Data, Collection<Data>>();
        var obsCollection = new ObservableCollection<Data>();
        var colCollection = new Collection<Data>();
        expander.DoSomethingWithColumn(obsTreeColumn);
        expander.DoSomethingWithColumn(colTreeColumn);
        expander.DoSomethingWithCollection(obsCollection);
        expander.DoSomethingWithCollection(colCollection);
        Console.ReadKey();
    }
}
class TreeExpander<T> where T : class {
    private int _rowCounter;
    public void DoSomethingWithColumn(object column) {
        // WHY ISN'T THIS CAST WORKING WITH A TreeColumn<T, ObservableCollection<T>>????
        var cast2 = column as TreeColumn<T, Collection<T>>;
        WriteLine("Cast to 'TreeColumn<T, Collection<T>>': ");
        WasCastSuccess(cast2);
        WriteLine("");
    }
    public void DoSomethingWithCollection(object collection) {
        var cast2 = collection as Collection<T>;
        WriteLine("Cast to 'Collection<T>': ");
        WasCastSuccess(cast2);
        WriteLine("");
    }
    private void WasCastSuccess(object o) {
        WriteLine(o != null ? "PERFECT!" : "Cast didn't work :(");
    }
    private void WriteLine(string msg) {
        _rowCounter++;
        Console.WriteLine(_rowCounter.ToString("00")+": "+msg);
    }
}

控制台输出为:

01: Cast to 'TreeColumn<T, Collection<T>>':
02: Cast didn't work :(
03:
04: Cast to 'TreeColumn<T, Collection<T>>':
05: PERFECT!
06:
07: Cast to 'Collection<T>':
08: PERFECT!
09:
10: Cast to 'Collection<T>':
11: PERFECT!
12:

我需要想出一些东西,所以输出的第 2 行读起来很完美!

在双类型泛型中对一种类型的 C# 向上转换不起作用

使用 out 关键字指定类型参数是协变的。

public interface ITreeColumn<T, out TValue> where TValue : Collection<T>
{
    // A lot declared in here..
}
public class TreeColumn<T, TValue> : ITreeColumn<T, TValue> where TValue : Collection<T>
{
    // A lot happens in here..
}