더듬이의 헬로월드

Hello, World!

프로그래밍 언어/C#

[C#] Action은 무엇이고, 어떻게 사용하는 걸까?

더듬이 2023. 2. 26. 15:13
728x90

https://learn.microsoft.com/ko-kr/dotnet/api/system.action-1?view=net-7.0

Action은 C#의 델리게이트(delegate) 중 하나로, 반환값이 없는 메서드를 참조하기 위한 형식입니다. 즉, 메서드를 변수로 전달하거나 다른 메서드의 인자로 사용할 때 유용하게 활용됩니다.

Action은 다음과 같이 선언됩니다.

public delegate void Action();

위의 코드에서, public은 액세스 수준 지정자입니다. delegate 키워드는 C#에서 델리게이트를 선언할 때 사용하는 키워드입니다. void는 반환값이 없는 메서드를 의미합니다. 그리고 Action은 델리게이트의 이름입니다.

Action은 인자를 갖지 않는 경우와 인자를 갖는 경우로 나뉩니다. 예를 들어, 반환값이 없는 메서드를 인자로 받는 Action은 다음과 같이 선언됩니다.

public delegate void Action();
public class Example
{
    public void DoSomething()
    {
        Debug.Log("Something is done.");
    }

    public void DoAnotherThing()
    {
        Debug.Log("Another thing is done.");
    }

    public void UseAction(Action action)
    {
        action();
    }
}

// Example 클래스의 인스턴스 생성 후 UseAction() 메서드에 DoSomething() 메서드 전달
Example example = new Example();
example.UseAction(example.DoSomething);

위의 예제에서, DoSomething()과 DoAnotherThing()은 반환값이 없는 메서드입니다. UseAction()은 반환값이 없는 메서드를 인자로 받는 메서드이며, action()을 호출하여 인자로 전달된 메서드를 실행합니다. example.UseAction(example.DoSomething)은 Example 클래스의 인스턴스를 생성하고, UseAction() 메서드에 DoSomething() 메서드를 전달하는 예제입니다.

인자를 갖는 Action은 다음과 같이 선언됩니다.

public delegate void Action<T>(T arg);
public class Example
{
    public void UseAction(Action<int> action)
    {
        action(10);
    }
}

// Example 클래스의 인스턴스 생성 후 UseAction() 메서드에 람다식 전달
Example example = new Example();
example.UseAction((int num) => Debug.Log(num));

위의 예제에서, UseAction()은 인자로 Action<int>를 받습니다. 이는 int형 인자를 받는 반환값이 없는 메서드를 참조하는 델리게이트입니다. action(10)은 인자로 10을 전달하여 Action<int> 델리게이트를 호출합니다. example.UseAction((int num) => Debug.Log(num))은 Example 클래스의 인스턴스를 생성하고, UseAction() 메서드에 람다식을 전달하는 예제입니다. 이 예제에서, 람다식 (int num) => Debug.Log(num)은 int형 인자를 받아서 로그를 출력하는 메서드를 의미합니다.

728x90