通过引用调用动作 [英] Invoke Action by reference

查看:79
本文介绍了通过引用调用动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新手,看来我需要使用 Dictionary< string,Action>
所以我写了以下代码:

I'm new to C#, and it looks I need to use Dictionary<string, Action> So I wrote the below code:

using System;
using System.Collections.Generic;

public class Program
{   
    public static void Main()
    {       
        var functions = new Dictionary<string, Action<string[]>>();
        functions.Add("Foo", CountParameters);
        functions.Add("Bar", SomeOtherMethodName);

        Console.WriteLine("Hello World");

        Action<string[]> action;
        if (functions.TryGetValue("Foo", out action))
        {
            action();
            // What shall I write here to invoke the action!?
        }
        else
        {
            // No function with that name
        }               
    }

    public static void CountParameters(string[] args)
    {
        Console.WriteLine("Fn 1");
    }

    public static void SomeOtherMethodName(string[] args)
    {
        Console.WriteLine("Fn 2");
    }
}

我的问题分为2部分:


  1. 如果条件为真,应如何调用 Action

  2. 我知道操作 Func ,其中 void 返回,但看起来输入 args 是必须的,在我的情况下,我没有输入args 也不是输出,所以我需要 Action 还是其他东西?

  1. How shall I invoke the Action if the condition is true.
  2. I understood the Action is a Func with void return, but it looks an input args is a must, in my case, i do not have an input args nor an output so is Action what I need, or could be something else?


推荐答案

如果您的所有方法都不具有返回值,则 Action< string []> 很好。如果他们甚至不需要参数,则可以简单地使用非通用的 Action -delegate并省略 string []

If all your methods don't don't have return values, an Action<string[]> is fine. If they even don't require parameters, you could simply use the non-generic Action-delegate and leave out the string[]-parameter.

var functions = new Dictionary<string, Action>();
functions.Add("Foo", CountParameters);
...

关于调用:在代码中的实现方式如果省略了(不必要的) string [] 参数,则该代码段很好。只需调用从字典中获取的 Action -delegate,就像您已经在没有任何参数的情况下进行的操作一样: action();

Regarding the invocation: The way you've done it in your code snippet is fine if you leave out the (unnecessary) string[]-parameter. Just invoke the Action-delegate taken from the dictionary like you already did without any parameters: action();

除了附加方括号()外,您还可以调用 action.Invoke();

Instead of attaching the brackets () you could alternatively call action.Invoke();.

这篇关于通过引用调用动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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