如何将调用传递给函数?

时间:2011-12-28 16:54:14

标签: .net visual-studio-2010 c#-4.0

我需要将一个函数传递给另一个函数并在那里调用它。我使用以下代码:

namespace DelegateTest
{
    class Program
    {
        public class MySampleClass
        {
            public void click(string param)
            {
                System.Console.WriteLine(param + " click!");
            }

            public void flick(string param)
            {
                System.Console.WriteLine(param + " flick!");
            }
        }

        public static delegate void EventToWait(string param);

        public static void waitFor(EventToWait myEvent, string param)
        {
            // here is a **very** complex loop, which i would like wipe from main() function
            myEvent(param);
        }

        public static void Main(string[] args)
        {
            MySampleClass sc = new MySampleClass();
            EventToWait ev1 = sc.click;
            EventToWait ev2 = sc.flick;

            waitFor(ev1, "Button_1");
            waitFor(ev2, "Button_2");

            System.Console.ReadKey();
        }
    }
}

但我的编译器说,该委托不能是静态的。我怎么能处理这个问题?

2 个答案:

答案 0 :(得分:5)

好吧,只需删除static关键字:

public delegate void EventToWait(string param);

答案 1 :(得分:0)

或者你可以声明:

public static void waitFor(Action<string> myEvent, string param)

并在您的主要电话中:

public static void Main(string[] args)
        {
            MySampleClass sc = new MySampleClass();
            EventToWait ev1 = sc.click;
            EventToWait ev2 = sc.flick;

            waitFor((k)=>sc.click(k), "Button_1");
            waitFor((k)=>sc.flick(k), "Button_2");

            System.Console.ReadKey();
        }

这避免了需要声明委托。