Why does Nullable<T> not match as a reference type for generic constraints [duplicate]

放肆的年华 提交于 2020-01-01 07:36:05

问题


Possible Duplicate:
Nullable type as a generic parameter possible?

I came across a very weird thing with generic type constraints. I have a class like this:

public SomeClass<T> where T:class
{
}

However, I've found I can't use nullable types as I'd expect:

new SomeClass<int?>();

I get an error that int? must be a reference type. Is Nullable really just a struct with syntactic sugar to make it look like a reference type?


回答1:


Nullable<T> is a struct (see MSDN) however it is the only struct that does not satisfy the struct constraint. Therefore, you cannot use a Nullable as a generic type parameter when either the class or struct constraints is used.

Nullable<T> is not just a struct with some syntatic sugar. It has special support in the CLR for some of its behavior. For example, it has special boxing behavior. Specifically, a nullable is never boxed. The underlying value is boxed. If the nullable is the null value (HasValue is false) then it is converted to a null reference. Also, conversion operators for any Nullable<T> to Nullable<U> are lifted from the conversions from T to U. These are features you wouldn't be able to implement yourself in .NET 1.0/1.1.



来源:https://stackoverflow.com/questions/13794554/why-does-nullablet-not-match-as-a-reference-type-for-generic-constraints

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