为什么我不能写Nullable< Nullable< int>> ;? [英] Why can't I write Nullable<Nullable<int>>?
问题描述
Nullable< T>
是:
[SerializableAttribute]
public struct Nullable<T> where T : struct, new()
约束其中T:struct
表示 T
只能是值类型。因此,我非常理解我无法写:
The constraint where T : struct
implies that T
can only be a value type. So I very well understand that I cannot write:
Nullable<string> a; //error. makes sense to me
因为 string
是一个引用类型,而不是值类型。但是我真的不明白为什么我不能写
Because string
is a reference type, not a value type. But I don't really understand why can't I write
Nullable<Nullable<int>> b; //error. but why?
为什么不允许?毕竟, Nullable< int>
是一种值类型,因此,它可以是 Nullablle< T> $ c $的类型参数。 c>。
Why is it not allowed? After all, Nullable<int>
is a value-type, and therefore, it can be type argument to Nullablle<T>
.
当我在ideone上编译它时,会出现此错误( ideone ):
When I compiled it on ideone, it gives this error (ideone):
错误CS0453:类型'int?'必须是不可为空的值类型,以便在通用类型或方法'System.Nullable'
中将其用作类型参数'T'编译失败:1个错误,0个警告
error CS0453: The type 'int?' must be a non-nullable value type in order to use it as type parameter 'T' in the generic type or method 'System.Nullable' Compilation failed: 1 error(s), 0 warnings
推荐答案
来自C#语言规范的4.1.10节:
From section 4.1.10 of the C# language spec:
相反, 不可为空的值类型 是除
System.Nullable< T>
及其速记T?
(对于任何T
),以及任何被约束为非空值类型的类型参数(即是,任何具有struct
约束的类型参数)。System.Nullable< T>
类型为T
(第10.1.5节)指定值类型约束。可空类型的基础类型可以是任何非空值类型。可为空的类型的基础类型不能为可为空的类型或引用类型。例如,int ??
和string?
是无效的类型。
A non-nullable value type conversely is any value type other than
System.Nullable<T>
and its shorthandT?
(for anyT
), plus any type parameter that is constrained to be a non-nullable value type (that is, any type parameter with astruct
constraint). TheSystem.Nullable<T>
type specifies the value type constraint forT
(§10.1.5), which means that the underlying type of a nullable type can be any non-nullable value type. The underlying type of a nullable type cannot be a nullable type or a reference type. For example,int??
andstring?
are invalid types.
这篇关于为什么我不能写Nullable< Nullable< int>> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!