如何为泛型提供对引用类型的约束

本文关键字:引用类型 约束 泛型 | 更新日期: 2023-09-27 18:03:00

我有这样的情况:

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为引用类型?

如何为泛型提供对引用类型的约束

典型的神话(即使我以前得到过)是从接口派生的类型是隐式引用类型,但实际上不是。结构也可以有接口。

因此,您应该添加更多的约束class来指示引用类型
public class FOO<T> where T : class, IBar