프로그래밍/C#

[C#] Action

Victory_HA 2025. 4. 21. 17:01
public static void DoSomething()
    {
        string msg1 = "hello";
        string msg2 = "world";

        Console.WriteLine(1);
        Action action = () => Console.WriteLine("hello world");
        action();

        Console.WriteLine(2);
        Action <string> action_Str = msg => Console.WriteLine($"{msg}");
        action_Str(msg1);

        Console.WriteLine(3);
        Action <string> action_Method1 = PrintMessage1;
        action_Method1(msg1);

        Console.WriteLine(4);
        Action <string, string> action_Method2 = PrintMessage2;
        action_Method2(msg1, msg2);

        Console.WriteLine(5);
        var list = new List<string> { "hello", "world" };
        list.ForEach(action_Str);
        list.ForEach(action_Method1);
    }

    public static void PrintMessage1(string msg)
    {
        Console.WriteLine($"PrintMessage1 :: {msg}");
    }

    public static void PrintMessage2(string msg1, string msg2)
    {
        Console.WriteLine($"PrintMessage2 :: {msg1} {msg2} ");
    }

결과 출력

1
hello world
2
hello
3
PrintMessage1 :: hello
4
PrintMessage2 :: hello world
5
hello
world
PrintMessage1 :: hello
PrintMessage1 :: world