参数类型null不能赋值给参数类型

本文关键字:参数 类型 赋值 null 不能 | 更新日期: 2023-09-27 18:17:19

我试图开发一个通用的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;
    }
}

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

在这种情况下我如何分配null ?

参数类型null不能赋值给参数类型

您需要告诉编译器TEclass,即引用类型。对于无界类型,TE也可以是一个值类型,它不能赋值给null:

public class BoundedListNode<TE> where TE : class
然后,您可以将null指定为构造函数中的参数:

根据Yuval的回答,确实,TE对类的泛型约束将启用null赋值。

分配空值的另一种方法是在创建新实例时使用default关键字。考虑下面的简化示例:

void Main()
{
   // p.CustomData will be null, use the default keyword.
   var p = new Person<Car?>(default);
  // p2.CustomData will be the new Car instance
   var p2 = new Person<Car>(new Car("Very fast Skoda"));
}

public class Person<TE>
{   
   public Person(TE customData)=> CustomData = customData;
   public TE CustomData {get;}
}
public record Car(string Name);