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

Các đại biểu trong C #

Một ủy nhiệm trong C # là một tham chiếu đến phương thức. Một đại biểu là một biến kiểu tham chiếu chứa tham chiếu đến một phương thức. Tham chiếu có thể được thay đổi trong thời gian chạy.

Các đại biểu đặc biệt được sử dụng để triển khai các sự kiện và các phương thức gọi lại. Tất cả các đại diện đều có nguồn gốc hoàn toàn từ lớp System.Delegate.

Hãy để chúng tôi xem cách khai báo ủy quyền trong C #.

delegate <return type> <delegate-name> <parameter list>

Hãy để chúng tôi xem một ví dụ để tìm hiểu cách làm việc với Ủy quyền trong C #.

Ví dụ

using System;
using System.IO;
namespace DelegateAppl {
   class PrintString {
      static FileStream fs;
      static StreamWriter sw;
      // delegate declaration
      public delegate void printString(string s);
      // this method prints to the console
      public static void WriteToScreen(string str) {
         Console.WriteLine("The String is: {0}", str);
      }
      // this method prints to a file
      public static void WriteToFile(string s) {
         fs = new FileStream("c:\\message.txt",
         FileMode.Append, FileAccess.Write);
         sw = new StreamWriter(fs);
         sw.WriteLine(s);
         sw.Flush();
         sw.Close();
         fs.Close();
      }
      // this method takes the delegate as parameter and uses it to
      // call the methods as required
      public static void sendString(printString ps) {
         ps("Hello World");
      }
      static void Main(string[] args) {
         printString ps1 = new printString(WriteToScreen);
         printString ps2 = new printString(WriteToFile);
         sendString(ps1);
         sendString(ps2);
         Console.ReadKey();
      }
   }
}

Đầu ra

The String is: Hello World