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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/110229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 14:18:18  来源:igfitidea点击:

How do nullable types work in C#?

提问by Mike Comstock

What is the behind-the-scenes difference between 'int?' and 'int'? Is 'int?' a somehow a reference type?

“int”之间的幕后区别是什么?和'int'?是“int”吗?不知何故是引用类型?

采纳答案by core

? 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

回答by Brad Wilson

In addition to "int?" being a shortcut for "Nullable", there was also infrastructure put into the CLR in order to implicitly and silently convert between "int?" and "int". This also means that any boxing operation will implicitly box the actual value (i.e., it's impossible to box Nullable as Nullable, it always results in either the boxed value of T or a null object).

除了“int?” 作为“Nullable”的快捷方式,CLR 中还加入了一些基础设施,以便在“int?”之间进行隐式和静默转换。和“int”。这也意味着任何装箱操作都会隐式装箱实际值(即,不可能将 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). http://bradwilson.typepad.com/blog/2008/07/creating-nullab.html

当您在编译时不知道 T(您只在运行时知道它)时,我在尝试创建 Nullable 时遇到了许多这些问题。http://bradwilson.typepad.com/blog/2008/07/creating-nullab.html

回答by Ash

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. This book is also excellent for many other areas of the .NET CLR internals.

整个第 18 章都致力于详细讨论 Nullable 类型。本书对于 .NET CLR 内部结构的许多其他领域也非常出色。

回答by simon9k

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

微软文档