我试图在不使用太多if语句(C#)的情况下加载不同的函数。我尝试过使用Lists,但对Unity使用Action
抛出了一个异常。我在这里找到了一个很好的c#解决方案:
var methods = new Dictionary<string, Action>()
{
{"method1", () => method1() },
{"method2", () => method2() }
};
methods["method2"]();
Action
也存在同样的问题
我进口
using System.Collections.Generic;
我想念什么?
除了为Dictionary
导入System.Collections.Generic
外,还需要为Action
导入System
。
将using System;
添加到文件顶部。
通常,在MSDN上查找该类型可以查看其完整的命名空间。在这种情况下,Action委托的MSDN页面指示其命名空间为"System"。因此,您必须在代码顶部添加using System;
指令,或者在代码中包含完整的命名空间。例如,如果您有,您可以在没有using
指令的情况下重写上面的代码
var methods = new System.Collections.Generic.Dictionary<string, System.Action>()
{
{"method1", () => method1() },
{"method2", () => method2() }
};
methods["method2"]();