【发布时间】:2018-06-12 23:10:33
【问题描述】:
我有一个操作的枚举,我想运行:
public enum theActions
{
action1,
action2
}
我想将它们存储在字典中:
public Dictionary<theActions, Action> _theActions { get; }
_theActions = new Dictionary<theActions, Action>
{
[theActions.action1] = () => action1Func()
};
对于每个操作,我都有自己的功能:
public void action1Func(int inParam)
{
//do whatever
}
稍后,我需要调用其中一个函数:
public void execAction(int inVar, Action action)
{
//inVar isn't the parameter I want to pass to the action. It's used, for something else.
action();
}
execAction(1, _theActions[theActions.action1]);
我不确定,如何更改我的代码以使 Action 在任何地方都接受参数,如果我需要一个不需要参数的操作怎么办?我是否必须在该函数中添加一个虚拟参数?
我知道了,到目前为止:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public enum theActions
{
action1,
action2
}
public Dictionary<theActions, Action<int>> _theActions { get; }
public void execAction(int inVar, Action<int> action)
{
//inVar isn't the parameter I want to pass to the action. It's used, for something else.
// action();
}
public Form1()
{
InitializeComponent();
_theActions = new Dictionary<theActions, Action<int>>
{
[theActions.action1] = (Action<int>)((int x) => action1Func(x))
};
}
public void action1Func(int inParam)
{
//do whatever
MessageBox.Show($"Hello ... inParam : {inParam}");
}
private void button1_Click(object sender, EventArgs e)
{
//This works manually
_theActions[theActions.action1].Invoke(12);
//But, I want the execAction to work
//execAction(1, _theActions[theActions.action1]);
}
}
}
它可以手动调用它。我只需要帮助进入 execAction() 并运行它。所以,关闭。
【问题讨论】:
-
我认为您对如何实现这一点感到困惑,因为您对自己真正想做的事情感到困惑。如果你不知道一个方法需要哪些参数,你将如何构建一种方法来提供它们?如果你的 executor 方法总是使用一个 int,那么如果这个 action 需要两个字符串,你会怎么做?
-
在这种情况下,它始终是单个 int 参数。
-
然后将您的操作设为
Action<int>。 -
我在所有 Action 语句之后添加
。我收到错误。 -
你有初始化时的参数信息
[theActions.action1] = () => action1Func()还是在调用动作时有这些参数?