我对 c# 还很陌生,只触及表面。由于我的技能相当有限,我已经达到了我能做的极限。我想用要调用的方法(包括参数)填充一个列表,并每秒或在任何其他时间段内调用这些方法。
我应该如何开始?我听说过代表,但我不确定它们是否是我需要的,或者它们是否适合我的目的。
对不起,如果这是常识。
我对 c# 还很陌生,只触及表面。由于我的技能相当有限,我已经达到了我能做的极限。我想用要调用的方法(包括参数)填充一个列表,并每秒或在任何其他时间段内调用这些方法。
我应该如何开始?我听说过代表,但我不确定它们是否是我需要的,或者它们是否适合我的目的。
对不起,如果这是常识。
正如 DeeMac 已经说过的,这似乎不是初学者或 C# 可能需要的东西,你最好解释一下为什么你认为你需要这样做。但是,要执行您所说的操作,您可以执行以下操作:
// Here we have the list of actions (things to be done later)
List<Action> ActionsToPerform;
// And this will store how far we are through the list
List<Action>.Enumerator ActionEnumerator;
// This will allow us to execute a new action after a certain period of time
Timer ActionTimer;
public ActionsManager()
{
ActionsToPerform = new List<Action>();
// We can describe actions in this lambda format,
// () means the action has no parameters of its own
// then we put => { //some standard c# code goes here }
// to describe the action
// CAUTION: See below
ActionsToPerform.Add(() => { Function1("Some string"); });
ActionsToPerform.Add(() => { Function2(3); });
// Here we create a timer so that every thousand miliseconds we trigger the
// Elapsed event
ActionTimer = new Timer(1000.0f);
ActionTimer.Elapsed += new ElapsedEventHandler(ActionTimer_Elapsed);
// An enumerator starts at the begining of the list and we can work through
// the list sequentially
ActionEnumerator = ActionsToPerform.GetEnumerator();
// Move to the start of the list
ActionEnumerator.MoveNext();
}
// This will be triggered when the elpased event happens in out timer
void ActionTimer_Elapsed(object sender, ElapsedEventArgs e)
{
// First we execute the current action by calling it just like a function
ActionEnumerator.Current();
// Then we move the enumerator on to the next list
bool result = ActionEnumerator.MoveNext();
// if we got false moving to the next,
// we have completed all the actions in the list
if (!result)
{
ActionTimer.Stop();
}
}
// Some dummy functions...
public void Function1(string s)
{
Console.WriteLine(s);
}
public void Function2(int x)
{
Console.WriteLine("Printing hello {0} times", x);
for (int i = 0; i < x; ++i)
{
Console.WriteLine("hello");
}
}
警告:在这里,这可以按预期工作,因为我们只是传入了一些常量值。但是,如果您不做如此微不足道的事情,事情就会变得棘手。例如考虑这个:
for (int i = 0; i < 10; ++i)
{
ActionsToPerform.Add(() => { Function2(i); });
}
这根本不会打印出您所期望的内容,这与闭包有关,这不是一个初学者主题。
这实际上是您应该认真考虑为什么需要这样做的第一个原因。如您所见,这里有一些复杂的概念通常不是初学者 C#...