在C#中使用动态键创建字典

时间:2016-09-07 08:23:27

标签: c# function dictionary unity3d

使用C / C ++进行编程时,我有时会使用一个字典,根据指定的键引用函数。但是,我真的不知道如何在C#中使用动态密钥

我正在使用Unity,当我在我的Unity项目上单击鼠标左键时,我想要调用一个函数,是否可能?

我真的很感激每一条评论。

3 个答案:

答案 0 :(得分:4)

我想你可以用这个: 首先为您的任务定义一个委托(在您的示例中按分配给键的作业):

public delegate void MyJob();

然后定义你的字典:

Dictionary<string, MyJob> myBinding = new Dictionary<string, MyJob>()
{
    { "left", delegate() { Console.WriteLine("Left Key pressed"); } },
    { "right", delegate() { Console.WriteLine("Right Key pressed"); } },
    { "up", delegate() { Console.WriteLine("Up Key pressed"); } },
    { "down", delegate() { Console.WriteLine("Down Key pressed"); } }
};

最后使用它:

public void Mapper(string pressedKey)
{
    myBinding[pressedKey]();
}

我希望这可以帮助您解决问题。如果您需要更多详细信息,请告诉我。

答案 1 :(得分:1)

当我看到&#34;动态键&#34;我认为有一些其他的东西,比如dynamic类型是字典的关键。但是,您可以轻松实现所需。在C#&#34;函数指针&#34;被称为delegates(但比指向函数的C指针更好),因此您需要一个字典,其中char类型作为键,其中一个代表作为值。在.net framework 4.0及更高版本中,有一些名为Func<T...>Action<T...>的预定义通用委托。基本上,如果您希望函数返回值,则使用Func,而Action将用于代替void方法。

所以你可以这样:

var keyMap = new Dictionary<char, Func<string, bool>>()
{
    {'w', MoveUp},
    {'s', MoveDown},
    {'a', s => true}, // using lambda expression
    {
        'd', delegate(string s)
        {
            if (string.IsNullOrWhiteSpace(s) == false)
            {
                //
            }
            return true;
        }
    } // using anonymous method
};

// then you can call those like this
var allow = keyMap['w']("some input");
if (allow)
{
    // .... 
}

public bool MoveUp(string input)
{
    return true;
}

public bool MoveDown(string input)
{
    return true;
}

以下是文档https://msdn.microsoft.com/en-us/library/bb549151(v=vs.110).aspx

答案 2 :(得分:1)

您可以使用Dictionary<KeyCode, System.Action>签名来完成此操作。获取所有代码并将其存储到System.Enum.GetValues(typeof(KeyCode));的数组中。然后,您可以使用keyCodeToFuncDic.Add(KeyCode.YourKeyCode, YourFunction);

将功能与功能配对

Update函数中,使用for循环遍历存储在开头的KeyCodes。检查是否按下了这些键。如果按下,请检查它是否在Dictionary中。如果字典中存在KeyCode,请使用按下的键Invoke Dictionary中的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(); } } } } 中的函数

代码:

-Error:Execution failed for task ':app:packageRelease'.

> Failed to read key keyname from store "release/example_keystore.jks": Cannot recover key