[英]How to store data objects that use 2 keys to look up a value
I need to tie 3 types of things together:我需要将 3 种类型的东西联系在一起:
The context of my project is that I have a video game state machine that exists in a single class.我的项目的背景是我有一个视频游戏 state 机器,它存在于单个 class 中。 I have several switch statements that I am trying to replace.
我有几个要替换的 switch 语句。 Each state has a set of functions associated with it, such as Enter() and Exit().
每个 state 都有一组与之关联的函数,例如 Enter() 和 Exit()。
In English, I want to say, "for ___ state, call ___ type of function" and then it calls the actual function.用英语,我想说,“对于___ state,调用___类型的函数”然后它调用实际的function。 For example, I'd like to do something like this:
例如,我想做这样的事情:
Lookup [states.attacking] [stateFunctions.enter];查找 [states.attacking] [stateFunctions.enter];
where this would return a call to "void Attacking_Enter()"这将返回对“void Attacking_Enter()”的调用
You could use a你可以使用一个
Dictionary<states, Dictionary<stateFunctions, Action>> Lookup = new Dictionary<states, Dictionary<stateFunctions, Action>>();
so you can look up and execute via eg所以你可以通过例如查找和执行
// 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();
Careful while filling it: Make sure to initialize the inner Dictionary
(s) before adding elements to it eg填充时小心:确保在向其添加元素之前初始化内部
Dictionary
(s),例如
Lookup[states.enter] = new Dictionary<stateFunctions, Action>();
Lookup[states.enter][stateFunctions.attack] = Attacking_Enter;
Or initialize them all in one go like eg或者将它们全部初始化在一个 go 中,例如
private void Initialize ()
{
Lookup = new Dictionary<states, Dictionary<stateFunctions, Action>>
{
{states.enter, new Dictionary<stateFunctions, Action>
{
{stateFunctions.attack, Attacking_Enter},
...
}
},
...
}
}
var dict = Dictionary<Dictioanry<T1, T2>, T3>();
where T1, T2 and T3 are your desired data types.其中 T1、T2 和 T3 是您想要的数据类型。
var dict = new Dictionary<Tuple<T1, T2>, T3>();
Or Class object which implement GetHashCode if needed或 Class object 如果需要,实现GetHashCode
var dict = new Dictionary<ClassObj, T3>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.