C# 如何在没有值的情况下向字典添加键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18685674/
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-10 12:55:49  来源:igfitidea点击:

How add key to dictionary without value?

c#dictionarykeyadd

提问by Iran_Girl

in normally we should add keyand valuetogether in dictionary type. like:

通常我们应该将key和加value在一起dictionary type。喜欢:

myDict.Add(key1, value1);
myDict.Add(key2, value2);

I want to know, Is there any way to add keyfirst, then insert its value? (not both of them at the same time)

我想知道,有没有办法先添加key,然后插入value?(不是两个同时)

采纳答案by Rotem

If the valuetype of the dictionary is nullable, you could add a null value:

如果value字典的类型可以为空,您可以添加一个空值:

myDict.Add(key1, null);

If the valueis non nullable, you can use a default value, either defaultor some out of range value, depending on your expected meaningful values.

如果value不可为空,则您可以使用默认值default或某个超出范围的值,具体取决于您预期的有意义的值。

myDict.Add(key1, default(int));
myDict.Add(key1, Int32.MinValue);

But

as mentioned in the comments, there is no discernible merit in doing this. You can add values at any time, there is no need to pre-initialize a dictionary with keys.

正如评论中提到的,这样做没有明显的优点。您可以随时添加值,无需使用键预先初始化字典。