【问题标题】:Store functions in List or Array in Unity3D在 Unity3D 中将函数存储在列表或数组中
【发布时间】:2013-06-23 21:19:08
【问题描述】:

我试图在不使用太多 if 语句 (C#) 的情况下加载不同的函数。我尝试使用 Lists,但 Unity 使用 Action 会引发异常。 我在这里找到了一个很好的 c# 解决方案:

var methods = new Dictionary<string, Action>()
          {
              {"method1", () => method1() },
              {"method2", () => method2() }
          };

methods["method2"]();

Action 也有同样的问题

我导入了

using System.Collections.Generic;

我错过了什么?

【问题讨论】:

    标签: c# methods dictionary unity3d


    【解决方案1】:

    除了System.Collections.Generic 对应Dictionary,还需要导入System 对应Action

    using System; 添加到文件顶部。

    一般来说,在 MSDN 上查找类型以查看其完整的命名空间。在这种情况下,Action delegate 的 MSDN 页面指示其命名空间是“系统”。因此,您要么必须在代码顶部添加 using System; 指令,要么在代码中包含完整的命名空间。因此,例如,您可以在没有using 指令的情况下重写上面的代码,如果您有:

    var methods = new System.Collections.Generic.Dictionary<string, System.Action>()
          {
              {"method1", () => method1() },
              {"method2", () => method2() }
          };
    
    methods["method2"]();
    

    【讨论】:

      猜你喜欢
      • 2016-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多