过去的问题主题并链接到完整代码HERE
我使用参数类创建我的字典,因此它可以包含两个string
值。现在我正在尝试在此类中的两个字符串中写TryGetValue
到out
:
public class DictionaryInitializer
{
public class DictionarySetup
{
public string theDescription { get; set; }
public string theClass { get; set; }
}
如您所见,theDescription
嵌套theClass
和DictionarySetup
。然后我会在这里使用该类创建词典:
public class DictionaryInit
{
//IS_Revenues data
public Dictionary<int, DictionarySetup> accountRevenue = new Dictionary<int, DictionarySetup>()
{
{ 400000, new DictionarySetup {theDescription="Call", theClass="Revenues"}}
};
public Dictionary<int, DictionarySetup> accountExpenses = new Dictionary<int, DictionarySetup>()
{
{790100, new DictionarySetup { theDescription="Currency Hedge", theClass="Other income/expense"}}
};
}
然后,我计划在字典上使用TryGetValue
的扩展方法:
public void DictionaryUseKey(int MapCode, int MapKey, int rowindex, Dictionary<int, DictionarySetup> AccountLexicon)
{
AccountLexicon[1] = new DictionarySetup();
DictionarySetup Classes;
DictionarySetup Descriptions;
//Saw the above code in another thread, not sure if it's what I should be doing but it seems pretty close to what I want, however, I don't know how to specify the DictionarySetup.theDescription for example;
AccountLexicon.TryGetValue(MapKey, out Classes);
{
//I want to be able to write theDescription and theClass into string variables for use below if the `TryGetValue` returns true, but it seems to me that it can only out one value? How does this work?
DGVMain.Rows[rowindex].Cells[3].Value = ?? how do I write something like... theValues.theDescription;
DGVMain.Rows[rowindex].Cells[11].Value = ?? how do I write something like... theValues.theClass;
}
}
最后,我在我的活动中调用扩展方法,如下所示:
private void btnMapper_Click(object sender, EventArgs e)
{
for (int rowindex = 0; rowindex < DGVMain.RowCount; rowindex++)
{
int accountKey = Convert.ToInt32(DGVMain.Rows[rowindex].Cells[2].Value);
int projCode = Math.Abs(Convert.ToInt32(DGVMain.Rows[rowindex].Cells[7].Value));
int deptCode = Math.Abs(Convert.ToInt32(DGVMain.Rows[rowindex].Cells[9].Value));
int AbsoluteKey = Math.Abs(accountKey);
while (AbsoluteKey >= 10) { AbsoluteKey /= 10; }
while (deptCode >= 10) { deptCode /= 10; }
theDictionary = new DictionaryInit();
DictionaryUseKey(deptCode, accountKey, theDictionary.accountRevenue);
}
}
答案 0 :(得分:2)
实际上TryGetValue
方法将返回一个布尔值,表示存在指定的键,如果找到该键,则相应的值将存储在out参数中。在您的情况下,out参数为Classes
,并在您的代码中定义如下:DictionarySetup Classes
。这意味着如果密钥出现在字典中,则相应的DictionarySetup
对象将存储在Classes
中,以便您可以从theDescription
访问theClass
和Classes
};请考虑以下代码:
if(AccountLexicon.TryGetValue(MapKey, out Classes))
{
DGVMain.Rows[rowindex].Cells[3].Value = Classes.theDescription;
DGVMain.Rows[rowindex].Cells[11].Value = Classes.theClass;
}