gpt4 book ai didi

c# - 可空和泛型

转载 作者:行者123 更新时间:2023-11-30 14:18:12 25 4
gpt4 key购买 nike

我正在尝试创建一个通用节点类,它可以包含任意数量的子节点、一个节点键字符串和一个可能为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com