gpt4 book ai didi

c# - 无法实习可为空的日期时间

转载 作者:行者123 更新时间:2023-11-30 20:15:54 24 4
gpt4 key购买 nike

我正在尝试实习一些传递的对象值,这些值会长时间保存在内存中。其中一些对象是 Nullable 值类型。我无法正确地实习 Nullable 值,我认为可能会发生某种我不理解的“有用”自动装箱。这是我应该通过的单元测试(假设 Nullalbes 表现得像对象)但不是:

[Test]
public void InternNullableType()
{
DateTime? one = new DateTime(2010, 2, 3, 4, 5, 6, DateTimeKind.Utc);
DateTime? two = new DateTime(2010, 2, 3, 4, 5, 6, DateTimeKind.Utc);

// should be equal, but not reference equal
Assert.False(ReferenceEquals(one, two));
Assert.True(one.Equals(two));

// create an interning dictionary
Dictionary<DateTime?, DateTime?> intern = new Dictionary<DateTime?, DateTime?>();
intern[one] = one; // add 'one', this will be the value we hand out
two = intern[two]; // intern the value of two

// values should be equal, and reference qual
Assert.True(one.Equals(two));

// this fails when it passes for objects
Assert.True(ReferenceEquals(one, two));
}

这是怎么回事?

最佳答案

可空类型是结构,而不是对象。它们是可以分配为空的特殊结构。所以实习不会像处理字符串那样工作,因为 string是引用类型。

当您检索可为 null 的对象的值时,装箱的值将被取消装箱,并使用该值创建新的可为 null 的实例。这就是为什么 ReferenceEquals返回 false .

来自docs :

When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the Nullable object, not the Nullable<T> object itself. That is, if the HasValue property is true, the contents of the Value property is boxed. When the underlying value of a nullable type is unboxed, the common language runtime creates a new Nullable<T> structure initialized to the underlying value.

关于c# - 无法实习可为空的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51956478/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com