C#将函数的名称插入到字符串arr中 [英] C# insert functions's names into string arr
问题描述
我有要执行的功能列表,我想使用循环来执行此操作,
我不知道怎么做,你能帮我一个吗?
我th to to to将mt函数的名称插入到arr中,然后在循环中运行
这样的东西
string [] s1 = new string [3] {func1,func2 ,func3};
for(int i = 0; i< s1.lengh; i ++)>
这里我要调用函数...如何我可以吗?
你有更好的报价吗?
谢谢。
I have list of function to execute and I want to use loop to do it,
I dont how to this , can you avise me?
I thoght to insert the names of mt functions to arr and than run in loop
something like this
string[] s1 = new string[3] {"func1", "func2", "func3"};
for(int i=0;i<s1.lengh;i++)>
here I want to call the function ... how ca I do it?
Do you have better offer?
Thanks.
推荐答案
您好,
请查看动态调用方法,给定方法名称和类名称的字符串 [ ^ ]文章可在CodeProject上找到。
问候,
Hello,
Please have a look at Dynamically Invoke A Method, Given Strings with Method Name and Class Name[^] article available here on CodeProject.
Regards,
这似乎是一个非常糟糕的反射使用,重要的是要注意反射很慢,如果你拼写错误名称或更改函数名称,你将得到错误。
更好的想法是使用代理,这是一个例子(这是未经过测试,但你明白了):
This seems like a really bad use of reflection, its important to note that reflection is slow and if you spell a name wrong or change a function name you will get errors.
A better idea is to use a delegate, here is an example (this is not tested, but you get the idea):
class TestClass
{
delegate void FunctionTemplate();
void Function1()
{
//Do whatever here
}
void Function2()
{
//Do whatever here
}
void Function3()
{
//Do whatever here
}
public void LoopFunctions(int times)
{
FunctionTemplate[] array = new FunctionTemplate[] { Function1, Function2, Function3 };
for(int i = 0; i < times; i++)
array[i]();
}
}
这很简单,没有使用匿名方法过度设计或使用慢速反射,如果你将Function1重命名为BlowUpMars,它将在数组中重命名它,无论你在何处使用它。
This is very simple, not over-engineered with anonymous methods or using slow reflection, plus if you rename Function1 to BlowUpMars it will rename it in the array and wherever else you are using it.
示例调用静态方法:
Example invocation static methods:
void Main()
{
var methods = typeof(MyFuncClass)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Select(x => new
{
Name = x.Name,
Action = new Action(() => x.Invoke(null, null))
})
.ToList();
foreach (var method in methods)
{
Console.WriteLine("Executing {0}:", method.Name);
method.Action.Invoke();
}
}
class MyFuncClass
{
public static void DoStuff()
{
Console.WriteLine("DoStuff result");
}
public static void DoAnotherStuff()
{
Console.WriteLine("DoAnotherStuff result");
}
}
这篇关于C#将函数的名称插入到字符串arr中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!