gpt4 book ai didi

c# - 泛型类中的可空类型

转载 作者:太空宇宙 更新时间:2023-11-03 17:16:49 25 4
gpt4 key购买 nike

我需要创建一个类似这样的类:

class GenericClass<T>
{
public T[] Arr {get; }
public GenericClass(int n)
{
Arr = new T[n];
for (int i = 0; i < n; i++)
{
Arr[i] = null;
}
}
}

但是有一个编译错误:

CS0403 Cannot convert null to type parameter 'T' because it could be a non-nullable value type. Consider using 'default(T)' instead.

我不想使用default(T),因为它可能与正常值相同但我需要区分。我不知道类型,所以我不能使用最小值。如何使用 null?

最佳答案

泛型的问题是他们必须考虑 T 是任何字面意思的可能性,包括不能为 null 的类型(值类型包括基元和结构) .为了将泛型参数限制为可以null的类型,您需要添加约束:

class GenericClass<T> where T : class
{
public T[] Arr { get; private set; }
public GenericClass(int n)
{
Arr = new T[n];
for (int i = 0; i < n; i++)
{
Arr[i] = null;
}
}
}

或者,您可能根本不想处理 null。相反,您可以替换

Arr[i] = null;

Arr[i] = default(T);

它会正常工作。 default(T) 将为任何可为 null 的类型返回 null,为任何不可为 null 的类型返回默认值。 (int 为 0,bool 为 false,等等)

编辑: 作为另一种选择,您可以在内部使用 Nullable 包装器类型表示对象。 C# 允许使用 ? 运算符对此语法进行简写:

class GenericClass<T>
{
public T?[] Arr { get; private set; }
public GenericClass(int n)
{
Arr = new T?[n];
}
}

顺便说一句,使用这种方法,无需遍历数组的每个索引并将其设置为 null,因为 C# 会为您处理。

关于c# - 泛型类中的可空类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44117642/

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