定义Nullable<T>是:
[SerializableAttribute]
public struct Nullable<T> where T : struct, new()
Run Code Online (Sandbox Code Playgroud)
约束where T : struct意味着T只能是值类型.所以我很清楚我不能写:
Nullable<string> a; //error. makes sense to me
Run Code Online (Sandbox Code Playgroud)
因为string是引用类型,而不是值类型.但我真的不明白为什么我不能写
Nullable<Nullable<int>> b; //error. but why?
Run Code Online (Sandbox Code Playgroud)
为什么不允许?毕竟,Nullable<int>是一个值类型,因此,它可以是类型参数Nullablle<T>.
当我在ideone上编译它时,它会给出这个错误(ideone):
错误CS0453:类型'int?' 必须是非可空值类型才能在泛型类型或方法'System.Nullable'中将其用作类型参数'T'编译失败:1个错误,0个警告
有谁知道为什么这段代码不能编译?
Nullable<Nullable<int>> n = null;
Run Code Online (Sandbox Code Playgroud)
我意识到Nullable有一个约束
where T : struct
Run Code Online (Sandbox Code Playgroud)
但Nullable是结构.我也知道这个约束有一个限制"类型参数必须是一个值类型.可以指定除Nullable之外的任何值类型." (https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters).那么它是怎样工作的?这是在编译器级别解决的吗?
当我写作
Nullable<Nullable<DateTime>> test = null;
我收到编译错误:
The type 'System.Datetime?' must be a non-nullable value type in order to use it as a paramreter 'T' in the generic type or method 'System.Nullable<T>'
但Nullable<T>它是struct如此,它应该是不可空的.
所以我试着创建这个struct:
public struct Foo<T> where T : struct
{
private T value;
public Foo(T value)
{
this.value = value;
}
public static explicit operator Foo<T>(T? value)
{
return new Foo<T>(value.Value);
}
public static implicit operator T?(Foo<T> value)
{
return new Nullable<T>(value.value);
} …Run Code Online (Sandbox Code Playgroud)