Inconsistent behavior in C# 8 nullable reference type handling with generics

て烟熏妆下的殇ゞ 提交于 2020-01-24 07:57:11

问题


I have this code:

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;
}

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?


回答1:


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.

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

You need where T : class?, IDisposable?.



来源:https://stackoverflow.com/questions/59631254/inconsistent-behavior-in-c-sharp-8-nullable-reference-type-handling-with-generic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!