在C#中使用动态键创建字典 [英] Create dictionary with dynamic keys in C#

查看:642
本文介绍了在C#中使用动态键创建字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C/C ++进行编程时,有时我会使用一个字典,其中包含根据指定键对函数的引用.但是,我真的不知道如何在C#中拥有类似的功能,从而允许我动态键.

When programming with C/C++ I sometimes used to have a dictionary with references to functions according to the specified keys. However, I don't really know how to have something similar in C# allowing me dynamic keys.

我正在Unity上工作,例如,当我在Unity项目上按鼠标左键时,我想调用一个函数,这可能吗?

I'm working on Unity and I'd like for exemple to invoke a function when I press left mouse click on my Unity project, is it possible ?

我真的很感谢对此的所有评论.

I'd really appreciate every comments on this.

推荐答案

您可以使用Dictionary<KeyCode, System.Action>签名来实现.获取所有代码,然后使用System.Enum.GetValues(typeof(KeyCode));将它们存储到数组中.然后,您可以使用keyCodeToFuncDic.Add(KeyCode.YourKeyCode, YourFunction);

You can use Dictionary<KeyCode, System.Action> signature to accomplish that. Get all the code codes and store them into an array with System.Enum.GetValues(typeof(KeyCode));. You can then pair your keys with your functions with keyCodeToFuncDic.Add(KeyCode.YourKeyCode, YourFunction);

Update函数中,使用for循环遍历开头存储的KeyCodes.检查是否按下了这些键中的任何一个.如果按下,请检查它是否在Dictionary中.如果字典中存在KeyCode,请使用按下的键在Dictionary值中使用Invoke函数,该函数最终将调用存储在Dictionary中的函数.

In the Update function, use for loop to loop over the KeyCodes stored in the beginning. Check if any of those keys is pressed. If pressed, check if it is in the Dictionary. If the that KeyCode exist in the dictionary, use the pressed key to Invoke the function in the Dictionary value, which will eventually call the function that is stored in the Dictionary.

代码:

Dictionary<KeyCode, System.Action> keyCodeToFuncDic = new Dictionary<KeyCode, System.Action>();
Array allKeyCodes;

void Start()
{
    //Get all codecodes
    allKeyCodes = System.Enum.GetValues(typeof(KeyCode));

    //Register Keycodes to functios
    keyCodeToFuncDic.Add(KeyCode.Mouse0, myFunction); //Left mouse
    keyCodeToFuncDic.Add(KeyCode.Mouse1, myFunction2); //Right mouse
}

void myFunction()
{
    Debug.Log("Left Mouse Clicked");
}

void myFunction2()
{
    Debug.Log("Right Mouse Clicked");
}

void Update()
{
    foreach (KeyCode tempKey in allKeyCodes)
    {
        //Check if any key is pressed
        if (Input.GetKeyDown(tempKey))
        {
            //Check if the key pressed exist in the dictionary key
            if (keyCodeToFuncDic.ContainsKey(tempKey))
            {
                //Debug.Log("Pressed" + tempKey);

                //Call the function stored in the Dictionary's value
                keyCodeToFuncDic[tempKey].Invoke();
            }
        }
    }
}

这篇关于在C#中使用动态键创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆