协方差和逆变:如何在同一界面中使用两者?

时间:2017-05-18 12:42:38

标签: generics interface covariance contravariance variance

如何在我的界面中对泛型类型使用out参数,并将此类型作为方法的参数重用,还是作为非covariante函数的返回?

请参阅示例(我的实际案例是" 添加(T项)"其他是测试):

public interface ITestAdapter<out T>
{
    void Clear(); // Compile

    T GetItemAt(int index); // Compile

    void Add(T item); // ERROR:  Invalid variance: The type parameter 'T' must be contravariantly valid on 'ITestAdapter<T>.Add(T)'. 'T' is covariant.
    IList<T> GetInnerList(); //ERROR: Invalid variance: The type parameter 'T' must be invariantly valid on 'ITestAdapter<T>.GetInnerList()'. 'T' is covariant.

    IEnumerable<T> GetInnerAsEnumerable(); // Compile
}

public class TestAdapter<T> : ITestAdapter<T>
{
    public TestAdapter(IList<T> innerList)
    {
        this._innerList = innerList;
    }

    private readonly IList<T> _innerList;

    public void Clear()
    {
        this._innerList.Clear();
    }

    public void Add(T item)
    {
        this._innerList.Add(item);
    }

    public T GetItemAt(int index)
    {
        return this._innerList[index];
    }

    public IList<T> GetInnerList()
    {
        return this._innerList;
    }

    public IEnumerable<T> GetInnerAsEnumerable()
    {
        return this._innerList;
    }
}

public class A { }
public class AB : A { }

public class Test
{
    public static void Doy()
    {
        var list = new List<AB>();
        var typed = new TestAdapter<AB>(list);
        var boxed = default(ITestAdapter<A>);
        boxed = typed; // OK;
    }
}

0 个答案:

没有答案