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

C# - 익명 메서드

우리는 대리자가 대리자와 동일한 서명을 가진 모든 메서드를 참조하는 데 사용된다는 점에 대해 논의했습니다. 즉, 해당 대리자 개체를 사용하여 대리자가 참조할 수 있는 메서드를 호출할 수 있습니다.

익명 방법 코드 블록을 대리자 매개변수로 전달하는 기술을 제공합니다. 익명 메소드는 이름이 없고 본문만 있는 메소드입니다.

익명 메서드에서는 반환 형식을 지정할 필요가 없습니다. 메서드 본문 내부의 return 문에서 추론됩니다.

익명 방법 작성

익명 메서드는 대리자를 사용하여 대리자 인스턴스 생성과 함께 선언됩니다. 예어. 예를 들어,

delegate void NumberChanger(int n);
...
NumberChanger nc = delegate(int x) {
   Console.WriteLine("Anonymous Method: {0}", x);
};

코드 블록 Console.WriteLine("익명 메서드:{0}", x); 익명 메서드의 본문입니다.

대리자는 익명 메서드와 명명된 메서드 모두를 사용하여 동일한 방식으로, 즉 메서드 매개변수를 대리자 개체에 전달하여 호출할 수 있습니다.

예를 들어,

nc(10);

다음 예는 개념을 보여줍니다 -

라이브 데모
using System;

delegate void NumberChanger(int n);
namespace DelegateAppl {
   class TestDelegate {
      static int num = 10;
      
      public static void AddNum(int p) {
         num += p;
         Console.WriteLine("Named Method: {0}", num);
      }
      public static void MultNum(int q) {
         num *= q;
         Console.WriteLine("Named Method: {0}", num);
      }
      public static int getNum() {
         return num;
      }
      static void Main(string[] args) {
         //create delegate instances using anonymous method
         NumberChanger nc = delegate(int x) {
            Console.WriteLine("Anonymous Method: {0}", x);
         };
         
         //calling the delegate using the anonymous method 
         nc(10);
         
         //instantiating the delegate using the named methods 
         nc =  new NumberChanger(AddNum);
         
         //calling the delegate using the named methods 
         nc(5);
         
         //instantiating the delegate using another named methods 
         nc =  new NumberChanger(MultNum);
         
         //calling the delegate using the named methods 
         nc(2);
         Console.ReadKey();
      }
   }
}

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

Anonymous Method: 10
Named Method: 15
Named Method: 30

C 언어

  1. C# 추상 클래스 및 메서드
  2. C# 부분 클래스 및 부분 메서드
  3. C# 봉인된 클래스 및 메서드
  4. C# 메서드 오버로딩
  5. Python 익명/람다 함수
  6. 자바 익명 클래스
  7. 자바 8 - 기본 메소드
  8. C# - 메서드
  9. C# - 대리자
  10. EPA 방법 21이란 무엇입니까?