使用不同类的不同方法委派

时间:2016-02-08 06:23:28

标签: c#

using System;

 delegate int NumberChanger(int n);
 namespace DelegateAppl
 {
   class TestDelegate
   {
     static int num = 10;
    public static int AddNum(int p)
     {
      num += p;
      return num;
     }

     public static int MultNum(int q)
    {
      num *= q;
     return num;
    }
  public static int getNum()
  {
     return num;
  }

  static void Main(string[] args)
  {
     //create delegate instances
     NumberChanger nc1 = new NumberChanger(AddNum);
     NumberChanger nc2 = new NumberChanger(MultNum);

     //calling the methods using the delegate objects
     nc1(25);
     Console.WriteLine("Value of Num: {0}", getNum());
     nc2(5);
     Console.WriteLine("Value of Num: {0}", getNum());
     Console.ReadKey();
  }
}

在上面的代码函数中调用和调用函数在同一个类中....我们可以在单独的类中使用吗?

如果有可能请举个例子......

1 个答案:

答案 0 :(得分:0)

当然可以。

只需将您的方法放在一个单独的类中,然后创建一个实例来访问它们:

class Arithmetic
{
    int num = 10;
    public int AddNum(int p)
    {
        num += p;
        return num;
    }

    public int MultNum(int q)
    {
        num *= q;
        return num;
    }
}

现在调用方法:

class TestDelegate
{
    public delegate int NumberChanger(int n);

    static void Main(string[] args)
    {
        //create instance of class
        Arithmetic art = new Arithmetic();

        //create delegate instances
        NumberChanger nc1 = new NumberChanger(art.AddNum);  //call with reference
        NumberChanger nc2 = new NumberChanger(art.MultNum); //call with reference

        //calling the methods using the delegate objects

        //add
        Console.WriteLine("Value of Num: {0}", nc1(25)); //use it directly because your delegate returns a value

        //product
        Console.WriteLine("Value of Num: {0}", nc2(5)); //use it directly because your delegate returns a value

        Console.ReadKey();
    }
}

注意:您不需要getNum()方法,因为您已经从每个方法返回值,并且您的委托也会返回它。此外,我已从任何地方删除了static,因为它似乎需要它。