gpt4 book ai didi

c# - C# 编译器是否优化可空类型?

转载 作者:IT王子 更新时间:2023-10-29 04:48:41 26 4
gpt4 key购买 nike

任何人都可以阐明此单元测试在 Visual Studio 2013 中失败的原因吗?

[TestMethod]
public void Inconceivable()
{
int? x = 0;
Assert.AreEqual(typeof(int?), x.GetType());
}

最佳答案

您的测试失败是因为:

Calling GetType on a Nullable type causes a boxing operation to be performed when the type is implicitly converted to Object. Therefore GetType always returns a Type object that represents the underlying type, not the Nullable type.

您可以从 How to: Identify a Nullable Type 阅读更多内容.

上一篇文章中的一些例子:

int? i = 5;
Type t = i.GetType();
Console.WriteLine(t.FullName); //"System.Int32"

另请注意:

The C# is operator also operates on a Nullable's underlying type. Therefore you cannot use is to determine whether a variable is a Nullable type. The following example shows that the is operator treats a Nullable<int> variable as an int.

int? i = 5;
if (i is int) { ... } // true

您假设 C# 编译器正在优化可空类型是正确的。这是 Jon Skeet 的 C# in Depth 的引述这应该回答你的问题:

It’s only with respect to boxing and unboxing that the CLR has any special behavior regarding nullable types. In fact, the behavior was only changed shortly before the release of .NET 2.0, as the result of community requests.

An instance of Nullable is boxed to either a null reference (if it doesn’t have a value) or a boxed value of T (if it does). It never boxes to a “boxed nullable int”—there’s no such type.


StackOverflow 上有一个类似的帖子:Nullable type is not a nullable type?

关于c# - C# 编译器是否优化可空类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30989810/

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