使用列表中的参数保存方法调用并执行它们

时间:2013-11-08 13:53:07

标签: c# list reflection methods

我对c#很陌生,只是表面上看。由于我的技能相当有限,我刚刚达到了我能做的极限。我想填充一个列表,其中包含调用方法(包括参数),并且每秒或在任何其他时间段调用这些方法。

我应该如何开始?我听说过代表们,但我不确定他们是否是我需要的,或者他们是否适合我的目的。

很抱歉,如果这是常识性的。

1 个答案:

答案 0 :(得分:3)

正如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); });
}

这不会打印出你期望的内容,而是与closures有关,这是一个非常的初学者话题。

这实际上是您应该认真考虑为什么需要这样做的首要原因。正如你所看到的,这里有一些复杂的概念,通常不是初学者C#...