是什么?类型声明后的 C# 中的运算符是什么意思? [英] What does the ? operator mean in C# after a type declaration?
问题描述
我有一些带有以下数组声明的 C# 代码.注意 Color
之后的单个 ?
.
I have some C# code with the following array declaration. Note the single ?
after Color
.
private Color?[,] scratch;
在我的调查中,我发现如果你有这样的代码:
In my investigating I have found that if you you have code such as:
int? a;
变量 a
未初始化.您将在何时何地使用它?
The variable a
is not initialized. When and where would you use this?
推荐答案
?
只是语法糖,表示该字段为 Nullable.它实际上是 Nullable
.
?
is just syntactic sugar, it means that the field is Nullable. It is actually short for Nullable<T>
.
在 C# 和 Visual Basic 中,您可以使用?值类型后的符号.例如,整数?在 C# 或整数?在 Visual Basic 中声明了一个可以赋值的整数值类型空.
In C# and Visual Basic, you mark a value type as nullable by using the ? notation after the value type. For example, int? in C# or Integer? in Visual Basic declares an integer value type that can be assigned null.
您不能将 null
分配给值类型,int
作为值类型不能保存 null
值,int?
另一方面可以存储空值.
You can't assign null
to value types, int
being a value type can't hold null
value, int?
on the other hand can store null value.
Color
的情况也是如此,因为它是一个结构 (因此是值类型),并且它不能保存空值,Color?[,]
您正在制作一个可为空颜色的数组.
Same is the case with Color
, since it is a structure (thus value type) and it can't hold null values, with Color?[,]
you are making an array of nullable Color.
对于您的问题:
变量a"未初始化.您将在何时何地使用这个?
The variable 'a' is not initialized. When and where would you use this?
通过将 ?
与变量一起使用并不会使其使用 null
或任何其他值进行初始化,它仍然需要进行初始化.
By using ?
with variable doesn't make it initialized with null
or any other value, it is still has to be initialized.
int? a = null;
int b = null;//error since b is not nullable
这篇关于是什么?类型声明后的 C# 中的运算符是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!