Dlaczego wartość Nullable <T> jest dopuszczalna? Dlaczego nie można go odtworzyć?
Kiedy piszę
Nullable<Nullable<DateTime>> test = null;
Dostaję błąd kompilacji:
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>'
AleNullable<T>
jeststruct
więc to ma być niezawierające wartości.
Próbowałem to stworzyć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);
}
}
Teraz, kiedy piszę
Nullable<Foo<DateTime>> test1 = null;
Foo<Nullable<DateTime>> test2 = null;
Foo<DateTime> test3 = null;
Pierwsza linia jest w porządku, ale dla drugiej i trzeciej linii otrzymuję dwa następujące błędy kompilacji:
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>'
(tylko druga linia)
i
Cannot convert null to 'MyProject.Foo<System.DateTime?> because it is a non-nullable value type'
Foo<Nullable<DateTime>> test = new Foo<DateTime?>();
nie działa, jeśliNullable<DateTime>
jeststruct
.
Koncepcyjnie rozumiem dlaczegoNullable<T>
jest nieważne, unika takich rzeczyDateTime??????????
jednak nadal mogęList<List<List<List<List<DateTime>>>>>
...
Dlaczego więc to ograniczenie i dlaczego nie mogę odtworzyć tego zachowania wFoo<T>
? Czy to ograniczenie jest wymuszane przez kompilator, czy też nieNullable<T>
kod?
czytamto pytanie ale po prostu mówi, że nie jest możliwe, aby żadna z odpowiedzi nie mówiła zasadniczo, dlaczego nie jest to możliwe.