C#中:什么是字典中的[字符串]索引返回? [英] C#: What does the [string] indexer of Dictionary return?

查看:135
本文介绍了C#中:什么是字典中的[字符串]索引返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是 [字符串] 词典返回索引时的关键并不在字典存在吗?我是新的C#和我似乎无法找到一个参考不如的Javadoc。

What does the [string] indexer of Dictionary return when the key doesn't exist in the Dictionary? I am new to C# and I can't seem to find a reference as good as the Javadocs.

我能得到,还是我得到一个异常?

Do I get null, or do I get an exception?

推荐答案

如果你的意思是词典<的索引;字符串,SOMETYPE> ,那么你应该看到一个异常( KeyNotFoundException )。如果你不希望它错误:

If you mean the indexer of a Dictionary<string,SomeType>, then you should see an exception (KeyNotFoundException). If you don't want it to error:

SomeType value;
if(dict.TryGetValue(key, out value)) {
   // key existed; value is set
} else {
   // key not found; value is default(SomeType)
}

这篇关于C#中:什么是字典中的[字符串]索引返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆