Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ผู้แทนใน C #


ผู้รับมอบสิทธิ์ใน C # คือการอ้างอิงถึงวิธีการ ผู้รับมอบสิทธิ์คือตัวแปรประเภทการอ้างอิงที่เก็บการอ้างอิงถึงวิธีการ การอ้างอิงสามารถเปลี่ยนแปลงได้ที่รันไทม์

ผู้รับมอบสิทธิ์จะใช้เฉพาะสำหรับการดำเนินการเหตุการณ์และวิธีการโทรกลับ ผู้รับมอบสิทธิ์ทั้งหมดมาจากคลาส System.Delegate โดยปริยาย

มาดูวิธีการประกาศผู้รับมอบสิทธิ์ในภาษา C# กัน

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

ให้เรามาดูตัวอย่างเพื่อเรียนรู้วิธีการทำงานกับ Delegates ใน C#

ตัวอย่าง

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

ผลลัพธ์

The String is: Hello World