你可以创建一个字典(假设操作码是一个整数
Dictionary<int, Action> actions = new Dictionary<int, Action>();
actions[7] = () => Console.WriteLine("hello World");
执行操作码“7”你可以这样做
actions[7]();
如果你想让它更健壮:
Action action;
if (actions.TryGetValue(7, out action))
action();
// else illegal opcode
如果你想从文件中加载动作字典,那就有点复杂了
你可以通过这样的字典调用静态方法ConsoleApplicationTest.Program.MyMethod()
namespace ConsoleApplicationTest
{
public class Program
{
public static void MyMethod()
{
Console.WriteLine("MyMethod called");
}
}
}
字典可以是这样的
Dictionary<int, MethodInfo> dynamicActions = new Dictionary<int, MethodInfo>();
dynamicActions[7] = Assembly.GetExecutingAssembly().GetType("ConsoleApplicationTest.Program").GetMethod("MyMethod", BindingFlags.Public | BindingFlags.Static);
方法会这样调用
MethodInfo method;
if (dynamicActions.TryGetValue(7, out method))
method.Invoke(null, new object[0]);