gpt4 book ai didi

c# - 我如何给泛型一个引用类型的约束?

转载 作者:行者123 更新时间:2023-12-02 05:12:03 25 4
gpt4 key购买 nike

我有这种情况:

public class FOO<T> where T : IBar
{
private T _xxx;
public Y(T xxx)
{
if (xxx == null) throw new ArgumentNullException("xxx");
_xxx = xxx;
}
}

public interface IBar
{
string XString { get; }
}

在构造函数中,我正在检查 T 是否为 null。编译器正确地警告我,我正在检查可能是值类型的东西上的 null,因为 IBar 可以由结构实现。

如何将 T 约束为引用类型?

最佳答案

典型的神话(甚至我以前也有)是从接口(interface)派生的类型是隐式引用类型,但实际上不是。 Struct 也可以有接口(interface)。

因此,您应该添加更多约束 class 以指示为引用类型

public class FOO<T> where T : class, IBar

关于c# - 我如何给泛型一个引用类型的约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15289559/

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