使用泛型处理 C# 8 可空引用类型的行为不一致
Inconsistent behavior in C# 8 nullable reference type handling with generics
我有这个代码:
public T? Foo<T>()
where T : class?
{
return null;
}
它给出了符合逻辑且符合预期的错误:
A nullable type parameter must be known to be a value type or non-nullable reference type. Consider adding a 'class', 'struct', or type constraint.
现在我再添加一个约束:
public T? Foo<T>()
where T : class?, IDisposable // Could be any interface I guess
{
return null;
}
现在有趣的是,错误刚刚消失了。虽然在我看来我们确实有冲突的约束,因为接口是 non-nullalbe
而 class?
是。
我是不是遗漏了什么或者编译器有问题?
泛型类型约束 where T : IDisposable
表示“T
必须不可为空并且必须实现 IDisposable
”。如果您有多个具有不同可空性的泛型类型约束,则仅当所有约束都可为空时,总体约束才可为空。
因此 class?
可以为 null 的事实被 IDisposable
不可以为 null 的事实所覆盖。
你需要where T : class?, IDisposable?
.
我有这个代码:
public T? Foo<T>()
where T : class?
{
return null;
}
它给出了符合逻辑且符合预期的错误:
A nullable type parameter must be known to be a value type or non-nullable reference type. Consider adding a 'class', 'struct', or type constraint.
现在我再添加一个约束:
public T? Foo<T>()
where T : class?, IDisposable // Could be any interface I guess
{
return null;
}
现在有趣的是,错误刚刚消失了。虽然在我看来我们确实有冲突的约束,因为接口是 non-nullalbe
而 class?
是。
我是不是遗漏了什么或者编译器有问题?
泛型类型约束 where T : IDisposable
表示“T
必须不可为空并且必须实现 IDisposable
”。如果您有多个具有不同可空性的泛型类型约束,则仅当所有约束都可为空时,总体约束才可为空。
因此 class?
可以为 null 的事实被 IDisposable
不可以为 null 的事实所覆盖。
你需要where T : class?, IDisposable?
.