산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> C 언어

C# - 대리자

C# 대리자는 C 또는 C++에서 함수에 대한 포인터와 유사합니다. 대리인 메소드에 대한 참조를 보유하는 참조 유형 변수입니다. 런타임에 참조를 변경할 수 있습니다.

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

대리인 선언

대리자 선언은 대리자가 참조할 수 있는 메서드를 결정합니다. 대리자는 대리자와 동일한 서명을 가진 메서드를 참조할 수 있습니다.

예를 들어 대리인을 생각해 보십시오.

public delegate int MyDelegate (string s);

앞의 대리자는 단일 문자열이 있는 모든 메서드를 참조하는 데 사용할 수 있습니다. 매개변수를 지정하고 int를 반환합니다. 유형 변수.

대리자 선언 구문은 -

입니다.
delegate <return type> <delegate-name> <parameter list>

대리인 인스턴스화

대리자 유형이 선언되면 대리자 개체는 new 키워드 및 특정 방법과 연결됩니다. 대리자를 만들 때 인수가 new 표현식은 메소드 호출과 유사하게 작성되지만 메소드에 대한 인수가 없습니다. 예를 들어 -

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

다음 예제에서는 정수 매개 변수를 사용하고 정수 값을 반환하는 메서드를 참조하는 데 사용할 수 있는 대리자의 선언, 인스턴스화 및 사용을 보여줍니다.

라이브 데모
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();
      }
   }
}

위의 코드를 컴파일하고 실행하면 다음과 같은 결과가 생성됩니다. -

Value of Num: 35
Value of Num: 175

대리인의 멀티캐스팅

대리자 개체는 "+" 연산자를 사용하여 구성할 수 있습니다. 구성된 대리자는 자신이 구성된 두 대리자를 호출합니다. 동일한 유형의 대리자만 구성할 수 있습니다. "-" 연산자는 구성된 대리자에서 구성 요소 대리자를 제거하는 데 사용할 수 있습니다.

대리자의 이 속성을 사용하여 대리자가 호출될 때 호출될 메서드의 호출 목록을 만들 수 있습니다. 이것을 멀티캐스팅이라고 합니다. 대리인의. 다음 프로그램은 대리자의 멀티캐스팅을 보여줍니다 -

라이브 데모
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 nc;
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);
         
         nc = nc1;
         nc += nc2;
         
         //calling multicast
         nc(5);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}

위의 코드를 컴파일하고 실행하면 다음과 같은 결과가 생성됩니다. -

Value of Num: 75

대리인 사용

다음 예제에서는 대리자를 사용하는 방법을 보여줍니다. 대리자 printString 문자열을 입력으로 받고 아무 것도 반환하지 않는 메서드를 참조하는 데 사용할 수 있습니다.

이 대리자를 사용하여 두 가지 메서드를 호출합니다. 첫 번째 메서드는 문자열을 콘솔에 출력하고 두 번째 메서드는 파일에 출력합니다 -

라이브 데모
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

C 언어

  1. C# Hello World - 첫 번째 C# 프로그램
  2. C# 키워드 및 식별자
  3. C# 변수 및 (기본) 데이터 형식
  4. C# 연산자
  5. C 프로그래밍의 사용자 정의 함수 유형
  6. C의 함수에 배열 전달
  7. 대표단이 인간의 기술을 대체하지 않고 증강을 촉구함에 따라 Economist Innovation Summit의 놀라움 중 백병전
  8. C++ 변수 및 유형:int, double, char, string, bool
  9. C - 기능
  10. C - 비트 필드