跨类/文件传递委托方法

时间:2012-03-28 04:18:19

标签: c# class methods delegates

我在另一个文件的类中有一个方法,我想采用动态方法。我在协商设置方面遇到了一些困难。任何帮助将不胜感激,谢谢!

例如......

文件#1:

class DoSomethingClass
{
    // define delegate
    public delegate void DelegateMethod();

    public void Main()
    {
        DelegateMethod d = Func1;       
        AnotherClass.CallsDynamicMethod("Test1", d);

        d = Func2;
        AnotherClass.CallsDynamicMethod("Test2", d);

        // will this work?
        // AnotherClass.CallsDynamicMethod("Test3", DoSomethingClass.instance.Func3);
    }


    // candidate methods for delegation
    void Func1()
    {   Console.WriteLine("calling Func1"); }

    void Func2()
    {   Console.WriteLine("calling Func2"); }   

    public void Func3()
    {   Console.WriteLine("calling Func3"); }   
}    


文件#2:

class AnotherClass
{   
    public static void CallsDynamicMethod(string words, DelegateMethod dynamicMethod)
    {
        Console.WriteLine("this is a " + words + " to call...");
        dynamicMethod();
    }
}

1 个答案:

答案 0 :(得分:2)

希望这能解决您的问题

 class Program
{
    static void Method()
    {
        Console.WriteLine("Method");
    }

    static void Main(string[] args)
    {
        Action a = Method;

        MyClass.SomeMethod(a);
        MyClass.SomeMethod(Method);

        Console.ReadLine();
    }
}

class MyClass
{
    public static void SomeMethod(Action del)
    {
        del();
    }
}