當我寫爲什麼Nullable <T>可以爲空?爲什麼它不能被複制?
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
:當我寫
Nullable<Foo<DateTime>> test1 = null;
Foo<Nullable<DateTime>> test2 = null;
Foo<DateTime> test3 = null;
第一行是確定
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);
}
}
,但現在第二行和第三行,我得到了以下兩個編譯錯誤:
The type 'System.DateTime?' must be a non-nullable value type in order to use it as a parameter 'T' in the generic type or method 'MyProject.Foo<T>'
(僅限第二行)
和
Cannot convert null to 'MyProject.Foo<System.DateTime?> because it is a non-nullable value type'
Foo<Nullable<DateTime>> test = new Foo<DateTime?>();
如果Nullable<DateTime>
是struct
不工作也不事件。
概念,我可以理解爲什麼Nullable<T>
是空的,它避免了像DateTime??????????
東西,但是我仍然可以有List<List<List<List<List<DateTime>>>>>
...
那麼,爲什麼這個限制,爲什麼我不能重現Foo<T>
這種行爲?這個限制是由編譯器執行還是在Nullable<T>
代碼中的內在?
我讀this question但它只是說這是不可能的答案根本無法說出爲什麼這是不可能的。
也許要通過Nullable到Foo 你必須把Foo 這個錯誤只是告訴你DateTime?不能作爲T傳遞的參數,因爲T是不可空的。如果T引用不可爲空的類型,則可以爲空,並且永遠不適合該聲明。 –
Amedio