在字典中使用类型“null”而不是 int

本文关键字:int null 字典 类型 | 更新日期: 2023-09-27 18:31:39

我需要声明一个包含 100 个键和值的字典(键是一个字符串,值是一个整数)。每个键都将是一个网格引用:A1、B6 等。我知道一些网格的确定值。我想通过将 int 值设置为 null 来在程序开始时为每个值添加一个键和一个值,但它不允许这样做。我该怎么办?

在字典中使用类型“null”而不是 int

在 int 后添加 '?' 使其成为可为空的类型

Dictionary<string, int?> myDictionary = new Dictionary<string, int?>();
null

是一个类型,它是一个值(用于引用),每个引用类型都可以分配给它。

因此,如果我正确阅读了您的帖子,您就有了:

 Dictionary< String, Int32 > // or Dictionary<string,int>

将其更改为 Int32?(语法糖表示Nullable<Int32>)。您还可以使用 { { key, value } } 语法来初始化字典,而不是重复调用 .Add( key, value ) ,如下例所示:

Dictionary< String, Int32? > dict = new Dictionary< String, Int32? > {
     { "A1", null },
     { "A2", null },
     { "A3", null },
     { "A4",   16 },
     { "A5",  123 },
     // etc
};