Nullable<int?> is not possible, Why not? [duplicate]

て烟熏妆下的殇ゞ 提交于 2019-12-10 10:31:22

问题


Excuse me if its a silly question, I am trying to get a better understanding of Nullable types in .Net.

From what i notice from Microsoft source code (using ReSharper), I understand that Nullable is a struct and T needs to be a struct

public struct Nullable<T> where T : struct

Now, I tried to do something like this

public struct CustomNullable<T> where T : struct
{
}
public class CustomNullableClass<T> where T : struct
{
}

And I get an error when I compile:

  Nullable<int?> a = null;
  Nullable<Nullable<int>> a1 = null;

For the above mentioned code I get an error 'Only non-nullable value types could be underlying of System.Nullable', but how is this enforced in the Nullable type ?

And for

   CustomNullable<int?> a2 = null;
   CustomNullableClass<int?> a3 = null;

I get an error 'The type System.Nullable must be non-nullable value type in order to use it as parameter T '.

I am bit confused now, can some one help me understand whats going on or have I not understood something ?

Thanks a lot in advance.

EDIT: If structs are value types and value types can't be null, how can a Nullable be a struct?

Credit : spender


回答1:


Actually, it's an internal hack somewhere in the C# compiler (guessing). You cannot replicate it in your own classes. If you make your own type, using the exact same IL, it will not enforce that additional hidden constraint.




回答2:


There is special compiler support specifically for Nullable. You're not capable of reproducing a number of different possible behaviors of Nullable with a custom struct. One of those behaviors is the one that you've mentioned here, that Nullable doesn't meet the generic constraint for a struct despite being a struct.



来源:https://stackoverflow.com/questions/24612399/nullableint-is-not-possible-why-not

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