기본 콘텐츠로 건너뛰기

[C#] C# 대리자(delegate)의 발전


C# 1.0에서는 코드의 다른 위치에 정의된 메서드를 사용하여 명시적으로 초기화하는 방식으로 대리자의 인스턴스를 만들었습니다. C# 2.0에서는 대리자 호출에서 실행될 수 있는 이름 없는 인라인 문 블록을 작성하는 방법으로 무명 메서드의 개념을 소개했습니다. C# 3.0에서는 개념적으로 무명 메서드와 비슷하지만 더 간결하고 표현이 다양한 람다 식을 소개했습니다. 이러한 두 기능을 함께 익명 함수라고 합니다. 일반적으로 .NET Framework의 버전 3.5 이상을 대상으로 하는 애플리케이션은 람다 식을 사용해야 합니다.

다음 예제에서는 C# 1.0에서 C# 3.0까지 대리자 만들기의 발전을 보여 줍니다

class Test
{
    delegate void TestDelegate(string s);
    static void M(string s)
    {
        Console.WriteLine(s);
    }

    static void Main(string[] args)
    {
        // Original delegate syntax required
        // initialization with a named method.
        TestDelegate testDelA = new TestDelegate(M);

        // C# 2.0: A delegate can be initialized with
        // inline code, called an "anonymous method." This
        // method takes a string as an input parameter.
        TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };

        // C# 3.0. A delegate can be initialized with
        // a lambda expression. The lambda also takes a string
        // as an input parameter (x). The type of x is inferred by the compiler.
        TestDelegate testDelC = (x) => { Console.WriteLine(x); };

        // Invoke the delegates.
        testDelA("Hello. My name is M and I write lines.");
        testDelB("That's nothing. I'm anonymous and ");
        testDelC("I'm a famous author.");

        // Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:
    Hello. My name is M and I write lines.
    That's nothing. I'm anonymous and
    I'm a famous author.
    Press any key to exit.
 */

이 블로그의 인기 게시물

[C#] 연산자 목록(Operators)

[C#][DB][ADO.NET] SqlCommand

public partial class Form1 : Form     {         string strConn = "server=.\\SQLEXPRESS;database=example;uid=sa;pwd=12345";         SqlConnection Conn;         SqlDataAdapter dataAdapter;         DataSet dataSet;         public Form1()         {             InitializeComponent();         }         private void SqlCommandInit()         {             string strSelectSQL = "SELECT * FROM tblEx01";             dataAdapter.SelectCommand = new SqlCommand(strSelectSQL, Conn);                      string strInsertCommand = "INSERT INTO tblEx01 (name, age) VALUES (@name, @age)";             dataAdapter.InsertCommand = ne...

Visual Studio 단축키

문자 검색/치환 Ctrl + F  -> 검색 Ctrl + H  -> 치환 자동 들여쓰기(indent) Ctrl + K, Ctrl + D  -> 파일전체 Ctrl + K, Ctrl + F  -> 선택영역 코드개요 확장/축소 Ctrl + M, Ctrl + L  -> 파일전체 확장/축소 Ctrl + M, Ctrl + M  -> 선택영역 확장/축소 주석처리 Ctrl + K, Ctrl + C  -> 선택영역 주석화 Ctrl + K, Ctrl + U  -> 선택영역 주석 취소 함수정의로 이동 F12 커서 위치 이력 기록 Ctrl + - (마이너스)  -> 직전 커서위치로 이동 Ctrl + Shift + - (마이너스)  -> 다음 커서위치로 이동