【问题标题】:How to store data objects that use 2 keys to look up a value如何存储使用 2 个键查找值的数据对象
【发布时间】:2020-07-13 01:18:38
【问题描述】:

我需要将 3 种类型的东西联系在一起:

  1. 一个枚举(状态)
  2. 另一个枚举(函数类型)
  3. 函数引用。

我的项目的上下文是我有一个存在于单个类中的视频游戏状态机。我有几个要替换的 switch 语句。每个状态都有一组与之关联的函数,例如 Enter() 和 Exit()。

用英文,我想说“对于___状态,调用___类型的函数”,然后调用实际的函数。例如,我想做这样的事情:

查找 [states.attacking] [stateFunctions.enter];

这将返回对“void Attacking_Enter()”的调用

【问题讨论】:

    标签: c# dictionary unity3d lookup


    【解决方案1】:

    你可以用一个

    Dictionary<states, Dictionary<stateFunctions, Action>> Lookup = new Dictionary<states, Dictionary<stateFunctions, Action>>();
    

    因此您可以通过例如查找和执行

    // First Key finds the inner dictionary
    // Second key finds the action in the inner dictionary
    // ? makes sure you don't get NullReferenceExceptions (just in case)
    // Invoke() finally executed the stored action
    Lookup[states.enter][stateFunctions.attack]?.Invoke();
    

    填充时小心:确保在向其添加元素之前初始化内部Dictionary(s),例如

    Lookup[states.enter] = new Dictionary<stateFunctions, Action>();
    Lookup[states.enter][stateFunctions.attack] = Attacking_Enter;
    

    或者像这样一次性初始化它们

    private void Initialize ()
    {
        Lookup = new Dictionary<states, Dictionary<stateFunctions, Action>>
        {
            {states.enter, new Dictionary<stateFunctions, Action>
                           { 
                               {stateFunctions.attack, Attacking_Enter}, 
                               ...
                           }
            },
            ...
        }     
    }
    

    【讨论】:

      【解决方案2】:
       var dict = Dictionary<Dictioanry<T1, T2>, T3>();
      

      其中 T1、T2 和 T3 是您想要的数据类型。

      【讨论】:

      • 您不想将第二本字典作为值而不是键吗?
      【解决方案3】:

      你可以试试Tuple

      var dict = new Dictionary<Tuple<T1, T2>, T3>();
      

      或者如果需要实现GetHashCode的类对象

      var dict = new Dictionary<ClassObj, T3>();
      

      【讨论】:

      • Tuple 不支持 Lookup [states.attacking] [stateFunctions.enter] 等查询
      猜你喜欢
      • 2022-12-02
      • 2021-07-31
      • 2020-05-01
      • 2022-08-05
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多