简体   繁体   English

可空和泛型

[英]Nullable and generics

I'm trying to create a generic node class which can hold any number of children nodes, a string for the node key, and a data node which may or may not be null. 我正在尝试创建一个通用节点类,它可以容纳任意数量的子节点,一个节点键的字符串,以及一个可能为null但可能不为null的数据节点。 However, I'm having problems getting the syntax right to have it accept the generic into the generic parameter for Nullable. 但是,我遇到了使语法正确接受泛型为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>>();
    }
}

On compile time I get the following error messsage: 在编译时我得到以下错误消息:

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'必须是非可空值类型,以便在泛型类型或方法'System.Nullable'中将其用作参数'T'

Is there a way to guarantee that E is a non-nullable type, or some other way around this? 有没有办法保证E是一个不可为空的类型,或者其他方式?

You just need: 您只需要:

internal class TrieNode<E> where E : struct

The : struct clause limits E to value types excluding Nullable<> , which allows Nullable<E> or E? : struct子句将E限制为Nullable<>之外的值类型,它允许Nullable<E>E? to work fine. 工作正常。

Maybe try internal class TrieNode where E : struct 也许尝试内部类TrieNode,其中E:struct

I think that Nullable types need to be value types rather than reference types (Reference types are already nullable) 认为 Nullable类型需要是值类型而不是引用类型(引用类型已经可以为空)

Why not just declare the node to use object ? 为什么不直接声明节点使用object An object can refer to any data type, and can also be null. 对象可以引用任何数据类型,也可以为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM