使用不同类的不同方法进行委托

本文关键字:方法 同类 | 更新日期: 2023-09-27 18:33:41

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();
  }
}

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

如果可能的话,请举个例子......

使用不同类的不同方法进行委托

当然可以。

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

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,因为您似乎需要它。