gpt4 book ai didi

c# - 是什么?类型声明后的 C# 中的运算符是什么意思?

转载 作者:太空狗 更新时间:2023-10-29 18:07:27 27 4
gpt4 key购买 nike

我有一些带有以下数组声明的 C# 代码。请注意 Color 之后的单个 ?

private Color?[,] scratch;

在我的调查中,我发现如果您有如下代码:

int? a;

变量a 没有初始化。您会在何时何地使用它?

最佳答案

?只是语法糖,它意味着该字段是可空的。它实际上是 Nullable<T> 的缩写.

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?另一方面可以存储空值。

Color也是如此,因为它是一个结构(因此是值类型)并且它不能保存空值,Color?[,]您正在制作一个可为空的颜色数组。

针对您的问题:

The variable 'a' is not initialized. When and where would you use this?

通过使用 ? with 变量不会用 null 初始化它或任何其他值,它仍然需要初始化。

int? a = null; 

int b = null;//error since b is not nullable

关于c# - 是什么?类型声明后的 C# 中的运算符是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16773891/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com