상세 컨텐츠

본문 제목

Action Func

C#

by MJ_119 2024. 6. 21. 14:39

본문

둘다 델리게이트의 일종. using System;을 통해 사용 가능

 

액션 - 반환값이 없을때 사용

// 매개변수가 없는 Action
Action sayHello = () => Console.WriteLine("Hello, World!");
sayHello(); // "Hello, World!" 출력

// 매개변수가 하나인 Action
Action<string> greet = name => Console.WriteLine($"Hello, {name}!");
greet("Alice"); // "Hello, Alice!" 출력

// 매개변수가 두 개인 Action
Action<int, int> printSum = (x, y) => Console.WriteLine(x + y);
printSum(3, 4); // "7" 출력

 

using System;

class Program
{
    static void Main()
    {
        Action<string> printMessage = message => Console.WriteLine(message);
        ExecuteAction(printMessage, "Hello, World!");
    }

    static void ExecuteAction(Action<string> action, string message)
    {
        action(message);
    }
}

 

펑션 - 반환값이 있을때 사용 

// 매개변수가 없는 Func
Func<int> getNumber = () => 42;
int result = getNumber(); // result는 42

// 매개변수가 하나인 Func
Func<int, int> square = x => x * x;
int squaredResult = square(5); // squaredResult는 25

// 매개변수가 두 개인 Func
Func<int, int, int> add = (x, y) => x + y;
int sumResult = add(3, 4); // sumResult는 7
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
        List<int> squaredNumbers = numbers.ConvertAll(new Converter<int, int>(x => x * x));

        foreach (var number in squaredNumbers)
        {
            Console.WriteLine(number);
        }
    }
}

'C#' 카테고리의 다른 글

디자인패턴  (0) 2024.06.24
예외처리 ( try, catch, finally, throw )  (0) 2024.06.21
인터페이스(interface)  (0) 2024.06.21
프로퍼티(property)  (0) 2024.06.21
델리게이트, 이벤트  (0) 2024.06.20

관련글 더보기