기본 콘텐츠로 건너뛰기

[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#] C# 프로그램의 일반적인 구조(A skeleton of a C# program)

// A skeleton of a C# program  using System; namespace YourNamespace {     class YourClass     {     }     struct YourStruct     {     }     interface IYourInterface      {     }     delegate int YourDelegate();     enum YourEnum      {     }     namespace YourNestedNamespace     {         struct YourStruct          {         }     }     class YourMainClass     {         static void Main(string[] args)          {             //Your program starts here...         }     } } By Microsoft.MSDN :: .NET Guide Docs

[C#] 간결한 식(expression)

[ 기본 간결식 ] member => expression; (example 1 : 메서드) using System; public class Person { public Person(string firstName, string lastName) { fname = firstName; lname = lastName; } private string fname; private string lname; public override string ToString() => $"{fname} {lname}".Trim(); public void DisplayName() => Console.WriteLine(ToString()); } class Example { static void Main() { Person p = new Person("Mandy", "Dejesus"); Console.WriteLine(p); p.DisplayName(); } } (example 2 : 생성자) public class Location {    private string locationName;    public Location(string name) => Name = name;    public string Name    {       get => locationName;       set => locationName = value;    } } (example 3 : 종료자) using System; public class Destroyer {    public override string ToString() => GetT...