1

我为大型 WPF 应用程序中的一个问题准备了一个示例应用程序。

我遇到的问题是将 TreeColumn 实例的第二种类型obsTreeColumn转换为Collection. 正如您所看到的,当我只用一种类型执行此操作时,upcast 工作正常。该方法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 行显示为 PERFECT!

4

1 回答 1

3

使用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..
}
于 2013-09-30T00:15:58.703 回答