C# 编译器是否优化可空类型?
Is the C# compiler optimizing nullable types?
任何人都可以解释为什么这个单元测试在 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.
Whosebug 上有一个类似的帖子:Nullable type is not a nullable type?
任何人都可以解释为什么这个单元测试在 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.
Whosebug 上有一个类似的帖子:Nullable type is not a nullable type?