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
How add key to dictionary without value?
提问by Iran_Girl
in normally we should add key
and value
together 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 key
first, then insert its value
? (not both of them at the same time)
我想知道,有没有办法先添加key
,然后插入value
?(不是两个同时)
采纳答案by Rotem
If the value
type of the dictionary is nullable, you could add a null value:
如果value
字典的类型可以为空,您可以添加一个空值:
myDict.Add(key1, null);
If the value
is non nullable, you can use a default value, either default
or 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.
正如评论中提到的,这样做没有明显的优点。您可以随时添加值,无需使用键预先初始化字典。