[英]Why does the compiler allow instantiation of generic class both with a nullable and non-nullable generic parameter?
I have a project in ASP.NET Core 6.我在 ASP.NET Core 6 中有一个项目。
I have the <Nullable>enable</Nullable>
setting in the project.我在项目中有
<Nullable>enable</Nullable>
设置。
I have the following class:我有以下课程:
public class ResponseResult<T>
{
public T? Result{ get; set; }
}
I can instantiate the class with a nullable or non-nullable generic parameter and the compiler does not generate a warning about it:我可以使用可为空或不可为空的泛型参数实例化该类,并且编译器不会生成有关它的警告:
var a = new ResponseResult<WeatherForecast>();
var a2 = new ResponseResult<WeatherForecast?>();
My question is: why doesn't the compiler generate an error in the first case?我的问题是:为什么编译器在第一种情况下不产生错误?
Since public T? Result{ get; set; }
自
public T? Result{ get; set; }
public T? Result{ get; set; }
public T? Result{ get; set; }
is nullable, shouldn't I be allowed to instantiate this class only with a nullable generic parameter?是
public T? Result{ get; set; }
为空的,难道我不应该只用一个可以为空的泛型参数来实例化这个类吗?
This is the expected behaviour.这是预期的行为。 I don't see why it should be a problem.
我不明白为什么它应该是一个问题。
For <WeatherForecast>
, T
is WeatherForecast
and T?
对于
<WeatherForecast>
, T
是WeatherForecast
和T?
is WeatherForecast?
是
WeatherForecast?
. .
For <WeatherForecast?>
, both T
and T?
对于
<WeatherForecast?>
, T
和T?
are WeatherForecast?
是
WeatherForecast?
. .
When you declared the class this way:当您以这种方式声明类时:
public class ResponseResult<T>
{
public T? Result{ get; set; }
}
You didn't say "T must be nullable for the entire ResponseResult
class", you said "Result is a property of type T, and the property is nullable if T is a reference type".您没有说“整个
ResponseResult
类的 T 必须可以为空”,您说“结果是 T 类型的属性,如果 T 是引用类型,则该属性可以为空”。
As far as I know, there is no way to actually constrain the generic type argument to have to be nullable.据我所知,实际上没有办法将泛型类型参数限制为可以为空。 There is no need, as you can just use
T?
没有必要,因为您可以使用
T?
inside the class.课堂内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.