我有这样的情况:
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)派生的类型是隐式引用类型,但实际上并非如此。 结构也可以有接口(interface)。
因此,您应该添加更多约束class
来指示引用类型
public class FOO<T> where T : class, IBar
关于c# - 如何给泛型施加对引用类型的约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15289559/