c# - Nullable<long> 在从 long 赋值后不是 Nullable<long>

标签 c# .net nullable

<分区>

我对原语可空值有意外的行为。

我的测试代码:

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 the long? on the stack, and the boxing only gives us a boxed long

因此,在可为 null 的情况下,结果值是基本类型(请参阅 herehere)。

在这种情况下,没有理由调用 GetType不管怎样,因为我们知道它是long?

关于c# - Nullable<long> 在从 long 赋值后不是 Nullable<long>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65871442/

相关文章:

c# - 寻找Postsharp老挝的好教程/文档,了解 "Librarian"样本

c# - Assembly.GetExportedTypes 与 GetTypes

c# - 以下通过关闭取消订阅事件的模式会导致任何问题吗?

.net - .NET 中的可空类型缺少方法

kotlin - 传递 null 时,有没有办法在非可选参数上使用默认值?

ios - IBOutlet 属性应该标记为可空还是非空?

C# 将 CPU 保持在/接近指定的百分比使用率以进行测试

c# - 使用node对mongodb进行多次查询

c# - MVC 3(预览版 1)动态 View 模型

c# - 如何确定远程处理 channel 是否已注册