通过引用调用动作 [英] Invoke Action by reference
问题描述
我是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部分:
- 如果条件为真,应如何调用
Action
。 - 我知道
操作
是Func
,其中void
返回,但看起来输入args
是必须的,在我的情况下,我没有输入args
也不是输出
,所以我需要Action
还是其他东西?
- How shall I invoke the
Action
if the condition is true. - I understood the
Action
is aFunc
withvoid
return, but it looks an inputargs
is a must, in my case, i do not have aninput args
nor anoutput
so isAction
what I need, or could be something else?
推荐答案
如果您的所有方法都不具有返回值,则 Action< string []>
很好。如果他们甚至不需要参数,则可以简单地使用非通用的 Action
-delegate并省略 string [] $ c
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屋!