【发布时间】:2017-03-28 05:34:18
【问题描述】:
过去的问题线程和完整过去代码的链接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);
}
}
【问题讨论】:
-
我在您的问题中没有看到任何用户定义的扩展方法。
-
您只能使用带有 out-parameters 的变量(以及 ref-parameters)。从您的话看来,您似乎是在尝试使用属性。
-
@Amy 对不起,我不知道这些到底叫什么。职能?只是方法?术语扩展方法与我上面写的示例类似: DictionaryUseKey(deptCode, accountKey, theDictionary.accountRevenue);
-
'扩展方法'在 C# 中有一个非常特殊的含义:它是一个静态方法,可以像成员方法一样调用。它们可用于为现有类型提供附加功能,但它们本质上只是语法糖。不过,您并没有在这里使用它们。
-
@Arvayne 不需要道歉。毕竟,这就是我们在这里的原因。
标签: c# winforms dictionary extension-methods trygetvalue