存放在C#中的方法列表 [英] Storing a list of methods in C#
问题描述
我有,我想在一个特定的顺序调用方法的列表。因此,我希望将它们存储或以有序列表中或者在与指定的索引的表。这种方式名单是改变我们想改变来电订购当天唯一
I have a list of method that I would like to call in a specific order. Therefore I would want to store them either in an ordered list or in a table with a specified index. This way the list would be the only thing to change the day we want to change the call order.
我发现的这篇文章解释如何使用数组和代表去做。但我评价和其他一些地方,它也可以使用字典和或LINQ进行读取。有何意见?
I found this article explaining how to do it using an array and delegates. But I read in the comments and some other places that it could also be done using a Dictionary and or LinQ. Any advices ?
推荐答案
您可以定义动作
的对象,这是参返回无效
代表。每个动作指向一个方法
You can define Action
objects, which are parameterless delegates that return void
. Each action is a pointer to a method.
// Declare the list
List<Action> actions = new List<Action>();
// Add two delegates to the list that point to 'SomeMethod' and 'SomeMethod2'
actions.Add( ()=> SomeClass.SomeMethod(param1) );
actions.Add( ()=> OtherClass.SomeMethod2() );
// Later on, you can walk through these pointers
foreach(var action in actions)
// And execute the method
action.Invoke();
这篇关于存放在C#中的方法列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!