我正在尝试创建一个通用节点类,它可以包含任意数量的子节点、一个节点键字符串和一个可能为 null 也可能不为 null 的数据节点。但是,我在获得正确的语法以使其将泛型接受为 Nullable 的泛型参数时遇到问题。
internal class TrieNode<E>
{
Nullable<E> Data;
string Key;
List<TrieNode<E>> Children;
public TrieNode(E? data, string key)
{
Data = data;
Key = key;
Children = new List<TrieNode<E>>();
}
}
在编译时,我收到以下错误消息:
The type 'E' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'
有没有办法保证 E 是不可为 null 的类型,或者有其他方法可以解决这个问题?
最佳答案
你只需要:
internal class TrieNode<E> where E : struct
: struct
条款限制 E
值类型不包括Nullable<>
,它允许 Nullable<E>
或 E?
工作正常。
关于c# - 可空和泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4883015/