我正在尝试创建一个操作字典,然后在循环中运行它们。 This问题有帮助,但在将操作添加到词典时仍然出现编译错误: - No overload for 'Action' matches delegate 'Action'.
感谢您的帮助。
Dictionary<string, Action> dActions = new Dictionary<string, Action>();
// do the actions need to be created?
Action<string, int> actSpot = new Action<string, int>(oBSM.Spot);
Action<string, int> actDelta = new Action<string, int>(oBSM.Delta);
dActions["Spot"] = new Action(actSpot);
dActions["Delta"] = new Action(actDelta);
// or add action to dictionary?
dActions.Add("Spot", oBSM.Spot(string BookOrComp, int DP);
dActions.Add("Delta", oBSM.Delta(string BookOrComp, int DP);
foreach (var BookOrComp in ListBookOrComp)
{
foreach (string Key in dActions.Keys)
{
for (int DP = 1; DP <= 21; DP++)
{
dActions[Key]();
}
}
}
更新: 我仍然会在代码
中看到一些编译错误Dictionary<string, Action> dActions = new Dictionary<string, Action>();
// create actions
Action<string, int> actSpot = new Action<string, int>(oBSM.Spot);
Action<string, int> actDelta = new Action<string, int>(oBSM.Delta);
dActions["Spot"] = new Action(actSpot); // no overload for Action matches delegate Action
dActions["Delta"] = new Action(actDelta); // ditto
foreach (var BookOrComp in ListBookOrComp)
{
foreach (string Key in dActions.Keys)
{
for (int DP = 1; DP <= 21; DP++)
{
dActions[Key](BookOrComp,DP); // delegate Action does not take 2 arguments
}
}
}
答案 0 :(得分:2)
我在你的程序中看到了许多错误:
1-括号不平衡:
// or add action to dictionary?
dActions.Add("Spot", oBSM.Spot(string BookOrComp, int DP);
dActions.Add("Delta", oBSM.Delta(string BookOrComp, int DP);
您需要在那里添加右括号。此外,我不确定该语法是否正确,我创建了一个对象,然后将其添加到字典中。
2-该操作采用两个参数:一个字符串和一个int:
Action<string, int> actSpot = new Action<string, int>(oBSM.Spot);
Action<string, int> actDelta = new Action<string, int>(oBSM.Delta);
但你现在正在使用参数调用它:
foreach (var BookOrComp in ListBookOrComp)
{
foreach (string Key in dActions.Keys)
{
for (int DP = 1; DP <= 21; DP++)
{
dActions[Key](); // <<<-- where are the parameters?
}
}
}
我认为这是编译器抱怨的错误。
更新2:
Dictionary<string, Action> dActions = new Dictionary<string, Action>();
应定义为:
Dictionary<string, Action<string, int>> dActions
=新词典&gt;();
和
dActions["Spot"] = new Action(actSpot); // no overload for Action matches delegate Action
应该是
dActions["Spot"] = actSpot; // actSpot already created with new Action...
或:
dActions["Spot"] = new Action<string, int>(oBSM.Spot);
PS:
当你这样做时,你必须明白:
dActions["Delta"] = new Action(actDelta); // ditto
您正在调用Action
的构造函数,其参数类型为Action<string. int>
,而Action
没有该构造函数。