What does class? (class with question mark) mean in a C# generic type constraint?

血红的双手。 提交于 2020-02-04 01:46:53

问题


While I tried to find an answer to another question I noticed that this code compiles in C#:

public void Foo<T>(T obj)
    where T : class?
{
}

I did not manage to find in the documentation what it even means.


回答1:


It enforces that T has to be a nullable reference type.

The type you set in for T, must derive from object?.

It's a new feature in C#8, to explictly declare a type as nullable. if you have

 Add<T>(T tmp);

You document, it's OK to Add null;




回答2:


To allow your class return null value without CS864 warning you can rewrite your code a little bit

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

The question about class? is open GitHub issue right now, have a look here. class? constraint isn't implemented yet and therefore compiler threats it like regular class and generate A null literal introduces a null value when 'T' is a non-nullable reference type for now.

You can also refer to the The issue wit T? section in this article to see some details. The code sample above is recommended way to deal with nullable generic type



来源:https://stackoverflow.com/questions/59630532/what-does-class-class-with-question-mark-mean-in-a-c-sharp-generic-type-const

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