Computer >> Máy Tính >  >> Lập trình >> C#

Làm thế nào để khởi tạo các đại biểu trong C #?

Sử dụng từ khóa mới để khởi tạo đại biểu. Khi tạo một đại biểu, đối số được truyền cho biểu thức mới được viết tương tự như một lệnh gọi phương thức, nhưng không có đối số cho phương thức.

Ví dụ -

public delegate void printString(string s);
printString ps1 = new printString(WriteToScreen);

Bạn cũng có thể khởi tạo người được ủy quyền bằng phương pháp ẩn danh -

//declare
delegate void Del(string str);
Del d = delegate(string name) {
   Console.WriteLine("Notification received for: {0}", name);
};

Hãy để chúng tôi xem một ví dụ khai báo và khởi tạo một đại biểu -

Ví dụ

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

Đầu ra

Value of Num: 35
Value of Num: 175