내일배움캠프/TIL

[내배캠][Unity6기][TIL] C# 문법 종합 강의 4주차(3~4)

binary는 호남선 2024. 10. 5. 22:57

Preview

- Boxing과 Unboxing
- Delegate (대리자)
- Lambda (람다식)
- Func 과 Action
- LINQ (Language-Integrated Query)
- Nullable
- Null 병합 연산자
- StringBuilder


Boxing과 Unboxing

- boxing : 값 -> 참조

- unboxing : 참조(박싱된 객체) -> 값

int i = 123;      // a value type
object o = i;     // boxing
int j = (int)o;   // unboxing

참고 : https://learn.microsoft.com/ko-kr/dotnet/csharp/programming-guide/types/boxing-and-unboxing

Delegate (대리자)

- 메서드를 변수처럼 사용

- c++의 함수포인터와 유사한 개념

- 함수 시그니처가 동일해야함, 오버로딩과 달리 반환 타입까지 일치 필요

- 형식 매개변수 T를 이용해 더욱 다양한 활용 가능

- 하나의 대리자에 여러 메소드 (델리게이트 체이닝)

class Program
{
    // 콜백 대리자 선언
    public delegate void Callback(string message);
    // 콜백 대리자에 등록할 메소드 정의
    public static void DelegateMethod(string message)
    {
        Console.WriteLine(message);
    }
    static void Main(string[] args)
    {
        // 콜백 대리자에 메소드 등록
        Callback handler = DelegateMethod;

        // 대리자가 호출되면 그에 등록된 메소드 호출
        // handler 호출되었으므로 연결된 DelegateMethod 호출됨
        handler("Hello World");
    }
}

참고 : https://learn.microsoft.com/ko-kr/dotnet/csharp/programming-guide/delegates/?source=recommendations#delegates-overview

https://keumjae.tistory.com/172

Lambda (람다식)

- 이름 없는 메소드 만드는 방법

- 델리게이트와 함께 활용됨

- 코드를 간결하게 만듦

var IncrementBy = (int source, int increment = 1) => source + increment;

Console.WriteLine(IncrementBy(5)); // 6
Console.WriteLine(IncrementBy(5, 2)); // 7

참고 : https://learn.microsoft.com/ko-kr/dotnet/csharp/language-reference/operators/lambda-expressions#expression-lambdas

Func 과 Action

- 델리게이트를 대체하는 미리 정의된 제네릭 형식

Func

- 반환값 있는 메소드 나타내는 델리게이트

- 마지막 제네릭 매개변수 형식이 반환 타입, 이전 매개변수 형식은 인자의 타입

Func<int, int, int> sum = (a, b) => a + b;
Console.WriteLine(sum(3, 4));  // output: 7

Action

- 반환값 없는 메소드 나타내는 델리게이트

Action greet = delegate { Console.WriteLine("Hello!"); };
greet();

Action<int, double> introduce = delegate { Console.WriteLine("This is world!"); };
introduce(42, 2.7);

// Output:
// Hello!
// This is world!

참고 : https://learn.microsoft.com/ko-kr/dotnet/csharp/language-reference/operators/delegate-operator#code-try-1

LINQ (Language-Integrated Query)

- C# 언어에 직접 쿼리 기능을 통합하는 방식을 기반으로 하는 기술 집합

- 구조

var result = from 변수 in 데이터소스
             [where 조건식]
             [orderby 정렬식 [, 정렬식...]]
             [select 식];
// 데이터 소스
int[] numbers = { 5, 10, 8, 3, 6, 12 };

// 쿼리문
var numQuery =
    from num in numbers     // 데이터 소스 지정(numbers에서)
    where num % 2 == 0      // 조건식 지정(나머지 2 연산 값이 0인, 짝수인)
    orderby num             // 정렬(기본이 오름차순)
    select num;             // 조회할 데이터

// 쿼리 실행 및 결과
foreach (int num in numQuery)
{
    Console.Write($"{num} ");   // 6 8 10 12
}

참고 : https://learn.microsoft.com/ko-kr/dotnet/csharp/linq/get-started/write-linq-queries

Nullable

- null 값을 가질 수 있는 값 형식

- ? 연산자 사용해 본래 null을 가질 수 없는 값형식이 null 값을 가질 수 있도록 허용

// 일반(값형) 변수
int normalInt = 0;
// ERROR[CS0037] : noramlInt는 null을 허용하지 않는 형식
normalInt = null;

// nullable 형식 변수
int? nullalbleInt = null;

Null 병합 연산자

- null 병합 연산자 ??

- null이면 오른쪽 피연산자를, null이 아니면 왼쪽 피연산자 반환

- nullable 형식이 아닌 변수에 사용 불가

int? nullableInt1 = null;
int? nullableInt2 = 10;

Console.WriteLine(nullableInt1 ?? 0);   // 0
Console.WriteLine(nullableInt2 ?? 0);   // 10

StringBuilder

- 내부 버퍼 사용해 문자열 조작

- 메모리 할당 및 해제 오버헤드 감소

 

[ 주요 메서드 ]

  • Append : 문자열 뒤에 추가
  • Insert : 문자열 지정한 위치에 삽입
  • Remove : 지정한 위치의 문자열을 제거
  • Replace : 문자열의 일부를 다른 문자열로 대체
  • Clear : StringBuilder의 내용 모두 삭제
StringBuilder sb = new StringBuilder();

// 문자열 추가
sb.Append("Hello");
sb.Append("World"); // HelloWorld

// 문자열 삽입
sb.Insert(5, ", "); // Hello, World

// 문자열 치환
sb.Replace("World", "Life"); // Hello, Life

// 문자열 삭제
sb.Remove(4, 2);    // Hell Life

// 완성된 문자열 출력
string result = sb.ToString();
Console.WriteLine(result);

참고 : https://learn.microsoft.com/ko-kr/dotnet/api/system.text.stringbuilder?view=net-6.0