简体   繁体   English

在初始化C#时将参数传递给字典中的操作

[英]Pass arguments to an action in dictionary at initialization C#

I have a Dictionary which has KeyCode as a key and an Action<int> as value,h however I want to give the Action parameters at the initialization of the dictionary like this : 我有一个Dictionary ,其中有KeyCode作为键,并且有一个Action<int>作为值,h,但是我想在字典初始化时提供Action参数,如下所示:

    someDictionary = new Dictionary<KeyCode, Action<int>>()
    {
        {KeyCode.Alpha1, GoToCameraPosition(0) },
    };

How can I do that ? 我怎样才能做到这一点 ?

This is called currying . 这称为currying Note that the second type parameter to Dictionary has changed from your original: The action you create has no parameters, because the parameter for the action it calls is built into the anonymous lambda stored in the dictionary. 请注意, Dictionary的第二个类型参数与原始参数已更改:创建的动作没有参数,因为它调用的动作的参数内置在字典中存储的匿名Lambda中。

someDictionary = new Dictionary<KeyCode, Action>()
{
    {KeyCode.Alpha1, () => GoToCameraPosition(0) },
};

Call like so: 像这样打电话:

KeyCode key = KeyCode.Alpha1;
Action act = null;

if (someDictionary.TryGetValue(key, out act))
{
    //  act is a method that calls GoToCameraPosition(0)
    act();
}

Or 要么

foreach (var kvp in someDictionary)
{
    kvp.Value();
}

Or, if you're certain it's in there... 或者,如果您确定它在其中...

someDictionary[KeyCode.Alpha1]();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM