Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

C#에서 대리자란 무엇입니까?

<시간/>

C#의 대리자는 메서드에 대한 참조입니다. 대리자는 메서드에 대한 참조를 보유하는 참조 형식 변수입니다. 런타임에 참조를 변경할 수 있습니다.

대리자는 특히 이벤트 및 콜백 메서드를 구현하는 데 사용됩니다. 모든 대리자는 System.Delegate 클래스에서 암시적으로 파생됩니다.

C#에서 대리자를 선언하는 방법을 살펴보겠습니다.

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

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 a 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