在我的桌面 C#
应用程序中,我从字典开始。我希望能够检查这本字典的关键。如果字典有这个键,我想把它传递给一个方法。如果字典没有这个键,我想创建一个空白列表并将其传递给它。我该怎么做?
我收到错误消息“字典中不存在给定的键”。我可以添加一个默认值,使其永远不会为 null 吗?
// myDic was declared as a Dictionary<string, List<string>
// Here is how I call someFunction
string text = SomeFunction(stringValue1, stringValue2, myDic[field1.field2]);
// SomeFunction looks like this
string SomeFunction (string string1, string string2, List<string> ra)
{
// method
return stringResult;
}
最佳答案
根据评论更新。要传递一个可能存在也可能不存在的键,您可以这样做(假设值是一个列表):
// assuming the method we are calling is defined like this:
// public String SomeFunction(string string1, String string2, List<String> ra)
List<string> valueToPassOn;
if (_ra.ContainsKey(lc.Lc))
{
valueToPassOn = _ra[lc.Lc]
}
else
{
valueToPassOn = new List<string>();
}
string text = tooltip.SomeFunction(something1, something2, valueToPassOn);
是否要传递整个字典(如问题最初所读),而不管字典是否存在:
您有两个选择。要么像这样创建字典:
if (myDic == null)
{
// change var and var2 to the types of variable they should be, ex:
myDic = new Dictionary<string, List<string>>();
}
string text = SomeFunction(stringValue1, stringValue2, myDic);
或者,什么可能是更好的选择,在函数 SomeFunction 的声明中添加一个字典作为具有默认参数的变量。只需确保您的函数知道如果字典为 null 时该怎么做。
string SomeFunction(string string1, string string2, Dictionary dictionary = null)
{
// method here
}
关于c# 检查键是否存在于字典中然后传递它的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29826482/