C#在循环中运行public void函数

时间:2013-10-31 15:00:16

标签: c#

我有一个公共void函数列表,它获取一个参数来执行,我想用循环来做, 我不知道怎么做,你能告诉我吗? 我想将mt函数的名称插入到arr中,然后在循环中运行 像这样的东西

string[] s1 = new string[3] {"func1", "func2", "func3"};
for(int i=0;i<s1.lengh;i++)

这里我想调用这个函数......我怎么能这样做?

你有更好的报价吗? 感谢。

6 个答案:

答案 0 :(得分:3)

您可以通过使用委托来传递函数作为参数/参数:

Action<T> action1 = func1;
Action<T> action2 = func2;

其中T是参数的类型(例如int,string)

然后,您可以通过调用

来运行这些引用的函数
action1(t);
action2(t);

其中t是函数的参数。

要使此示例有用,请考虑创建操作列表:

List<Action<T>> actions = new List<Action<T>>();
actions.Add(action1); actions.Add(action2);
foreach (Action<T> action in actions)
{
    var t = param; // Replace param with the input parameter
    action(t);
}

当然,您还必须

using System;

在代码文件的顶部以引用Action。

另请参阅有关Action委托的MSDN文档:http://msdn.microsoft.com/en-us/library/018hxwa8.aspx

答案 1 :(得分:2)

您的第一个选择是使用委托(假设参数是整数):

var s1 = new Action<int>[3] { a => func1(a), a => func2(a), a => func3(a) }; // without quotes it creates a function pointer
for(int i=0;i<s1.Length;i++)
   s1[i](parameter); // call the delegate

如果在编译时不知道函数名,请使用reflection来调用方法:

var s1 = new string[3] {"func1", "func2", "func3"};
for(int i=0;i<s1.Length;i++)
   this.GetType().GetMethod(s1[i]).Invoke(this, new object[] { parameter });

请注意第二个示例中的this.GetType() - 如果方法是在其他类型上定义的,则最有可能使用typeof(OtherType)

答案 2 :(得分:2)

使用delegate。例如,要调用接受一个参数并且不返回任何值的方法(即返回void),请使用Action<T>委托。假设您希望它们都接受相同的参数类型,它看起来有点像这样:

public void Action1(int x) { ... }
public void Action2(int x) { ... }
public void Action3(int x) { ... }

...

Action<int>[] actions = new Action<int>[] { Action1, Action2, Action3 }
for (int i = 0; i < actions.Length; i++)
{
    actions[i](i);  // Invoke the delegate with (...)
}

进一步阅读

答案 3 :(得分:1)

我相信你想要做的事情可以通过一系列行动来实现。

假设每个函数的参数类型是整数,那么这就是它的外观:

List<Action<int>> functions = new List<Action<int>> {func1, func2, func3};

int i = 5;
foreach (Action<int> f in functions)
{
     f(i);
}

编辑:根据更新后的OP进行更新,指定循环应仅覆盖每个函数。

答案 4 :(得分:0)

var list = new List<Action<MyParameterType>>() {func1, func2, func3};
foreach(var func in list)
{
   func(someValue);
}

答案 5 :(得分:0)

string[] s1 = new string[3] {"func1", "func2", "func3"};
for(int i=0;i<s1.lengh;i++)

List<string, Func<string>> functionList = new List<string, Func<string>>();
functionList.Add(s1[0], ()=>{return "You called func1!";});
functionList.Add(s1[1], ()=>{return "You called func2!";});
functionList.Add(s1[2], ()=>{return "You called func3!";});

for(int i=0;i<s1.length;i++)
{
  string retVal = functionList[s1[i]].Invoke();
}
相关问题