C#类型参数约束不允许转换为约束

时间:2016-08-27 04:49:35

标签: c# generics type-constraints

所以我将我的代码推广到下面的例子,我得到以下编译错误。我的问题是'为什么不允许将引用分配回'容器'?'。我的假设是,通过将类型T限制为继承自Element,“this”应该很容易转换为Container<Element>。 这个代码的重点是在对象(它被遍地传递)需要引用它所包含的位置的情况下,在每个元素对象中保持对容器的引用。

Compilation error (line 16, col 23): Cannot implicitly convert type 'Container<T>' to 'Container<Element>'

如果我在包含'this'的行中添加一个类型转换,我会得到以下代码。

Compilation error (line 16, col 23): Cannot convert type 'Container<T>' to 'Container<Element>'

using System;

public class Element
{
    public int datum;
    public Container<Element> container;
}

public class Container<T> where T : Element {

    T[] data;

    public Container() {
        data = new T[1];
        data[0].datum = 4;
        data[0].container = this;
    }

}

0 个答案:

没有答案
相关问题