参数类型null不能分配给参数类型

1 c# generics null

我正在尝试开发一个通用的BoundedList类,为此我创建了一个通用的BoundedListNode类.我的BoundedList类如下:

class BoundedList<TE>
{
    private BoundedListNode<TE> _startNode;
    private BoundedListNode<TE> _lastUsedNode;
    protected Dictionary<TE, BoundedListNode<TE>> Pointer;

    public BoundedList(int capacity)
    {
        Pointer = new Dictionary<TE, BoundedListNode<TE>>(capacity);
        _startNode = new BoundedListNode<TE>(null);
        _lastUsedNode = _startNode;
    }
}
Run Code Online (Sandbox Code Playgroud)

在_startNode的构造函数中,我收到错误"Argument type null不能分配给参数类型TE".

在这种情况下如何指定null?

Yuv*_*kov 5

你需要告诉编译器TE是一个class,意思是一个引用类型.对于无界类型,TE也可以是值类型,不能赋值给null:

public class BoundedListNode<TE> where TE : class
Run Code Online (Sandbox Code Playgroud)

然后,您将能够null在构造函数中指定为参数: