使用泛型的C#8可为空的引用类型处理中的行为不一致 [英] Inconsistent behavior in C# 8 nullable reference type handling with generics

查看:175
本文介绍了使用泛型的C#8可为空的引用类型处理中的行为不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

public T? Foo<T>()
    where T : class?
{
    return null;
}

它给出了逻辑上和预期的错误:

It gives an error that is logical and expected:

必须知道可为空的类型参数是值类型或不可为空的引用类型.考虑添加类",结构"或类型约束.

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.

现在我再添加一个约束:

Now I add one more constraint:

public T? Foo<T>()
    where T : class?, IDisposable // Could be any interface I guess
{
    return null;
}

现在有趣的是,足够多的错误刚刚消失了.尽管在我看来,我们确实有冲突的约束,因为接口是non-nullalbe,而class?

Now interestingly enough error has just disappeared. Though it really seems to me we have conflicting constraints since interface is non-nullalbe while class? is.

我在这里缺少什么吗?还是编译器有问题?

Am I missing something here or is there a trouble with compiler?

推荐答案

通用类型约束where T : IDisposable表示"T必须不可为空,并且必须实现IDisposable".如果您有多个具有不同无效性的泛型类型约束,则仅当所有约束均可为空时,约束总体才能为空.

The generic type constraint where T : IDisposable means "T must be non-nullable and must implement IDisposable". Where you have multiple generic type constraints of differing nullabilities, the constraint overall is only nullable if all constraints are nullable.

class?可为空的事实被IDisposable不可为空的事实所覆盖.

So the fact that class? is nullable gets overridden by the fact that IDisposable is not.

您需要where T : class?, IDisposable?.

这篇关于使用泛型的C#8可为空的引用类型处理中的行为不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆