简体   繁体   English

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

[英]Is the C# compiler optimizing nullable types?

Can anybody shed any light on why this unit test is failing in Visual Studio 2013? 任何人都可以了解为什么这个单元测试在Visual Studio 2013中失败了?

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

Your test is failing because: 您的测试失败,因为:

Calling GetType on a Nullable type causes a boxing operation to be performed when the type is implicitly converted to Object . 在Nullable类型上调用GetType会导致在将类型隐式转换为Object时执行装箱操作。 Therefore GetType always returns a Type object that represents the underlying type, not the Nullable type. 因此, GetType始终返回表示基础类型的Type对象,而不是Nullable类型。

You can read more from How to: Identify a Nullable Type . 您可以从如何:识别可空类型中了解更多信息

Some examples taken from the previous article: 从前一篇文章中摘取的一些例子:

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

Also note that: 另请注意:

The C# is operator also operates on a Nullable's underlying type. C#的操作者也可为空的基本类型进行操作。 Therefore you cannot use is to determine whether a variable is a Nullable type. 因此,您无法使用is来确定变量是否为Nullable类型。 The following example shows that the is operator treats a Nullable<int> variable as an int. 以下示例显示is运算符将Nullable <int>变量视为int。

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

You are correct in presuming that the C# compiler is optimizing nullable types. 假设C#编译器正在优化可空类型,你是正确的。 Here's a quote from Jon Skeet's C# in Depth which should answer your question: 以下是Jon Skeet的深度C#的引用,它应该回答你的问题:

It's only with respect to boxing and unboxing that the CLR has any special behavior regarding nullable types. 只有在装箱和拆箱方面,CLR才有关于可空类型的任何特殊行为。 In fact, the behavior was only changed shortly before the release of .NET 2.0, as the result of community requests. 实际上,这种行为只是在.NET 2.0发布之前不久发生了变化,这是社区请求的结果。

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). Nullable的实例被装箱为空引用(如果它没有值)或盒装值T(如果有)。 It never boxes to a “boxed nullable int”—there's no such type. 它永远不会装入“盒装可空的int” - 没有这种类型。


There's a similar thread on StackOverflow: Nullable type is not a nullable type? StackOverflow上有一个类似的线程: Nullable类型不是可以为空的类型?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM