Languages/C#

C# - 대리자, 델리게이트(Delegate)

라큐브 2021. 11. 8. 01:14

델리게이트는 변수가 아닌 메서드를 매계변수로 전달해주는 것이다.

메서드를 전달해주는 역할이므로 대리자(메서드를 대신 전달)라고 한다.

 

메서드를 호출하는 유형

1. 기본 자료형 변수를 인자를 받는다.

2. 객체를 인자로 받는다.

3. 메서드를 인자를 받는다.

 

1. 기본 자료형 변수로 인자를 받는 경우

static void Main(string[] args)
{
    Sum(10, 20);
}

public void Sum(int x, int y)

{
    Console.WriteLine(x + y)
}

> 30

2. 객체를 인자로 받는 경우

class Computer

{
    public string CPU{ get; set; }
    public string GPU{ get; set; }
    public string Memory{ get; set; }
    public string SSD{ get; set; }
}



static void Main(string[] args)
{
    Computer com = new();
    Console.WriteLine(Mounting(com).CPU);
}



public Computer Mounting(Computer _com)
{
    _com.CPU = "Intel i9-12900K";
    _com.GPU= "RTX-3090";
    _com.Memory= "Samsung DDR4 16GB";
    _com.SSD = "Hynix P31";
}

> Intel i9-12900K

3. 메서드를 인자로 받는 경우

델리게이트를 사용하여 인자로 넘긴다.

 

1. 델리게이트 타입 선언

//delegate void(전달할 메서드의 반환 타입) MyDelegate(델리게이트 명)(int a, int b)(전달할 메서드의 매계변수);
delegate void MyDelegate(int a);

2. 델리게이트 할당

static void Main(string[] args)
{
    // 델리게이트 할당(연결)
    MyDelegate md = new MyDelegate(Sum);

    // 델리게이트 사용
    // 델리게이트를 호출하면 Sum 메서드가 실행
    md(10, 15);
}

// 델리게이트가 호출되면 실제 실행될 메서드

static void Sum(int a, int b)
{
    Console.WriteLine(a + b);
}

> 25

 

반응형