我想使用字典的值而不将其分配给变量:
Dictionary<int, string> LayoutByID = new Dictionary<int, string>() {
{ 0, "foo"},
{ 1, "bar"}
// ...
};
如果创建变量,我可以例如打印值:
string b;
LayoutByID.TryGetValue(1,out b);
print("Trying Dictionary to retrieve value for 1: " + b);
但我想知道是否有更简单的方法,例如:
print("Trying Dictionary to retrieve value for 1: " + LayoutByID.TryGetValue(1 [???]));
我知道我可以编写一个带有开关的函数,该开关也可以类似地工作,但是使用字典可能会更便宜,因为我的列表较长。谢谢你的建议!
您可以使用Dictionary
诸如var x = LayoutByID[0];
But的键访问,但是,如果其中Dictionary
不包含带有该键的条目,则会出现异常。
为了避免引发异常,您可以先使用LayoutByID.ContainsKey()
-检查密钥是否存在,然后针对这些情况编写逻辑:
if (LayoutByID.ContainsKey(0)) // Check if the key exists (replace 0 with whatever)
{
var x = LayoutByID[0]; // Access the value and do whatever with it
// ...
}
else
{
// Key doesn't exist:
// Do something else
}
或使用C#6.0,您也可以像这样打印
var key = -1;
var myString = string.Empty;
LayoutByID.TryGetValue(key, out myString);
Console.WriteLine($"Trying Dictionary to retrieve value for {key}: {myString ?? "Error: Invalid ID"}");
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句