简体   繁体   English

可空类型在 C# 中如何工作?

[英]How do nullable types work in C#?

What is the behind-the-scenes difference between 'int?' “int”之间的幕后区别是什么? and 'int'?和'int'? Is 'int?'是“int”吗? a somehow a reference type?不知何故是引用类型?

? ? wraps the value type (T) in a Nullable<T> struct:将值类型 (T) 包装在 Nullable<T> 结构中:

http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx

In addition to "int?"除了“int?” being a shortcut for "Nullable", there was also infrastructure put into the CLR in order to implicitly and silently convert between "int?"作为“Nullable”的快捷方式,CLR 中还加入了一些基础设施,以便在“int?”之间进行隐式和静默转换。 and "int".和“int”。 This also means that any boxing operation will implicitly box the actual value (ie, it's impossible to box Nullable as Nullable, it always results in either the boxed value of T or a null object).这也意味着任何装箱操作都会隐式装箱实际值(即,不可能将 Nullable 装箱为 Nullable,它总是导致装箱的 T 值或空对象)。

I ran into many of these issues when trying to create Nullable when you don't know T at compile time (you only know it at runtime).当您在编译时不知道 T(您只在运行时知道它)时尝试创建 Nullable 时,我遇到了许多这些问题。 http://bradwilson.typepad.com/blog/2008/07/creating-nullab.html http://bradwilson.typepad.com/blog/2008/07/creating-nullab.html

For one of the better "behind the scenes" discussions about Nullable types you should look at CLR Via C# by Jeffrey Richter.对于有关 Nullable 类型的更好的“幕后”讨论之一,您应该查看 Jeffrey Richter 的CLR Via C#

The whole of Chapter 18 is devoted to discussing in detail Nullable types.整个第 18 章都致力于详细讨论 Nullable 类型。 This book is also excellent for many other areas of the .NET CLR internals.本书对于 .NET CLR 内部结构的许多其他领域也非常出色。

I learned that you must explicitly cast a nullable value type to a none-nullable value type, as the following example shows:我了解到您必须将可空值类型显式转换为不可空值类型,如以下示例所示:

int? n = null;

//int m1 = n;    // Doesn't compile
int n2 = (int)n; // Compiles, but throws an exception if n is null

MS Document 微软文档

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

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