class NonNullable<T> where T : class { List<T> tlist = new List<T>(); public void Add(T t) { if (t == null) { throw new ArgumentNullException("t"); } tlist.Add(t); } } static void Main(string[] args) { NonNullable<string> nn = new NonNullable<string>(); nn.Add(null); } 没有这样的泛型约束,只可以运行时检查。
class NonNullable<T>
where T : class
{
List<T> tlist = new List<T>();
public void Add(T t)
{
if (t == null)
{
throw new ArgumentNullException("t");
}
tlist.Add(t);
}
} static void Main(string[] args)
{
NonNullable<string> nn = new NonNullable<string>();
nn.Add(null);
}
没有这样的泛型约束,只可以运行时检查。