如何从C#中的MethodInfo []转到Action <object>?

时间:2016-05-31 20:45:07

标签: c# reflection attributes methodinfo

我正在映射一个xbox控制器,并想让用户改变一个键在程序中执行什么操作。我使用带有键的字典作为ControllerEventArgs(自定义事件args),值是Action,这是按下按钮时将调用的函数。

除了一部分外,一切都已到位:我们可以打开一个包含所有按钮的组合框(A Pressed,A Released,B,X,Y等)并使用反射和属性我显示所有可能的方法(按钮可以做的动作)。所以用户继续选择它 - 但现在我在MethodInfo []中有方法名称,我需要它作为传递给/修改我的字典的Action。有什么办法吗?我不熟悉反思和属性。

字典定义为:

public Dictionary<ControllerEventArgs, Action<object>> ButtonMapping = 
    new Dictionary<ControllerEventArgs, Action<object>>(new ControllerComparison());

这是我按下按钮时的事件:

private void basicevent(object source, ControllerEventArgs e)
{
    if (!AltState)
    {
        if (ButtonMapping.ContainsKey(e))
        {
            ButtonMapping[e].Invoke(e);
        }
        else //debug
        {
            MessageBox.Show("Key not found in dictionary.\nButton Name: " + e.Name + "\nAction: " + e.Action + "\nAlt Mode: FALSE");
        }
    }
    else
    {
        if (AltButtonMapping.ContainsKey(e))
        {
            AltButtonMapping[e].Invoke(e);
        }
        else //debug
        {
            MessageBox.Show("Key not found in dictionary.\nButton Name: " + e.Name + "\nAction: " + e.Action + "\nAlt Mode: TRUE");
        }
    } 
}

这就是我试图修改字典值的地方(你可以看到我在附近尝试的注释东西)

private void SaveKeyMapping_Click(object sender, RoutedEventArgs e)
{
    ComboBoxItem item = (ComboBoxItem)KeySelection.SelectedItem;
    string SelectedItem = item.Content.ToString();
    string SelectedAction = AvailableActions.SelectedItem.ToString();
    AvailableActions.Items.Clear();
    CurrentAction.Items.Clear();
    if ((SelectedItem == "RightThumb Moved") || (SelectedItem == "LeftThumb Moved"))
    {
        //Joystick specific
    }
    else if ((SelectedItem == "RightTrigger Pressed") || (SelectedItem == "RightTrigger Released") || (SelectedItem == "LeftTrigger Pressed") || (SelectedItem == "LeftTrigger Released"))
    {
        //Trigger specific
    }
    else
    {
        //Button specific
        string[] SelectedButton = SelectedItem.Split(SelectedItem[1]);
        ControllerEventArgs args = new ControllerEventArgs { Name = SelectedButton[0], Action = SelectedButton[1] };

        //Convert MethodInfo to Action<object>....

        // Action<object> action = (Action<object>)Delegate.CreateDelegate(typeof(Action<object>), ButtonMethods[1]);
        //Action<object> ac = delegate(object instance) { ButtonMethods[0].Invoke(instance, null); };
        // Action ac = (Action)Delegate.CreateDelegate(typeof(Action), ButtonMethods[1]);
        Action<object> newaction = controller.LightControl;
        //change value in dictionary

        controller.ButtonMapping[args] = newaction;
    }
}

0 个答案:

没有答案