<分区>
我对原语可空值有意外的行为。
我的测试代码:
Nullable<long> value = long.Parse("5");
Type type = value.GetType();
// at this Point type is System.Int64 and not Nullable<System.Int64>
有没有可能,哪里value
保持 Nullable<System.Int64>
并且不会转换为常规 long
?
<分区>
我对原语可空值有意外的行为。
我的测试代码:
Nullable<long> value = long.Parse("5");
Type type = value.GetType();
// at this Point type is System.Int64 and not Nullable<System.Int64>
有没有可能,哪里value
保持 Nullable<System.Int64>
并且不会转换为常规 long
?
最佳答案
没有。您已经将其分配给 long?
变量。
当您调用 GetType()
时, 这个函数是在 System.Object
上定义的.因此要调用它,我们必须将值装箱。
You can see this by viewing the generated MSIL instructions for the
GetType()
call:
box System.Nullable<System.Int64>
call System.Object.GetType
So when it is boxed it actually pushes thelong?
on the stack, and the boxing only gives us a boxedlong
因此,在可为 null 的情况下,结果值是基本类型(请参阅 here 和 here)。
在这种情况下,没有理由调用 GetType
不管怎样,因为我们知道它是long?
关于c# - Nullable<long> 在从 long 赋值后不是 Nullable<long>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65871442/