C#교과서 마스터하기 36. 제네릭 클래스 만들기

min seung moon·2021년 7월 14일
0

C#

목록 보기
38/54

https://www.youtube.com/watch?v=iArf2vVafM4&list=PLO56HZSjrPTB4NxAsEP8HRk6YKBDLbp7m&index=71

1. 제네릭(Generics)

  • 이미 우리는 제네릭 클래스를 사용함
    • 이제, 직접 제네릭 클래스를 만들어 볼 시간!!!
  • 매개변수에 따른 형식
  • 무언가를 담아 놓을 컨테이너 역할
    • Cup of T
    • Cup<T>
  • 장점
    • 타입 안정
    • 성능
      • 박싱과 언박싱 필요 없음

2. 내장된 제네릭 리스트 클래스

  • 내장된 제네릭 클래스만으로도 충분
    • System.Collections.Generic 네임 스페이스
    • ArrayList<T>
    • List<T>
    • Stack<T>
    • Queue<T>
    • HashSet<T>
    • Ditionary<Tkey, TValue>

3. 제네릭 형식(Generic Types)

  • 제네릭 형식
    • 제네릭 형식은 하나 이상의 형식 매개 변수를 설정할 수 있는 형식
    • 형식 매개 변수(Type Parameter)는 넘어오는 형식에 따른 멤버의 형식이 결정
    • 형식 매개 변수는 T는 클래스 이름 뒤에 꺽쇠 괄호(angle brackets : <>)로 표시
    • 아래 코드는 List 클래스를 나타내는데, T는 어떠한 형식에 대한 리스트를 나타내는지를 의미하는 표시
    public class List<T>

4. 대리자, Action<T>와 Func<T, TResult>

01. Action<T>

  • 반환값이 없는 경우에는 사용자 정의 대리자(Custom Delegate)를 정의 하는 대신에 Action 대리자를 사용할 수 있음

02. Func<T, TResult>

  • 반환값이 필요한 경우에는 Func 대리자를 사용할 수 있음
  • 마지막 파라미터는 항상 리턴값을 나타냄

5. Generic Type 제약 조건

6. 프로젝트

01. 컬렉션 이니셜라이저

using System;
using static System.Console;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Reflection;

namespace testProject
{

    class Category
    {
        public int CategoryId { get; set; }
        public string CategoryName { get; set; }
    }

    class Program
    {         
        static void Main(string[] args)
        {
            List<string> colors = new List<string>() { "Red", "Blue" };

            // [1] 컬렉션 이니셜라이저를 사용하여 개체 여러 개를 초기화
            var categories = new List<Category>
            {
                new Category() {CategoryId = 1, CategoryName = "좋은 책"},
                new Category() {CategoryId = 2, CategoryName = "좋은 강의"},
                new Category() {CategoryId = 3, CategoryName = "좋은 컴퓨터"}
            };

            // [2] foreach 문으로 컬렉션 데이터를 출력
            foreach(var category in categories)
            {
                WriteLine($"{category.CategoryId} - {category.CategoryName}");
            }

        }
    }
}

02. 클래스<T> 형태로 제네릭 클래스 만들기

using System;
using static System.Console;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Reflection;

namespace testProject
{
    // 제네릭 클래스 : T에 지정한 형식으로 클래스와 멤버의 성질이 결정
    // [1] 클래스<T> 형태로 제네릭 클래스 만들기
    class Cup<T>
    {
        public T Content { get; set; }
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    class Program
    {         
        static void Main(string[] args)
        {
            var text = new Cup<string>();
            // text.Content = 1234;
            text.Content = "1234";

            var number = new Cup<int>();
            // number.Content = "1234";
            number.Content = 1234;

            var person = new Cup<Person>();
            person.Content = new Person { Name = "M", Age = 25 };
            WriteLine($"{person.Content.Name} - {person.Content.Age}");
        }
    }
}


03. 형식 매개 변수 2개 사용

using System;
using static System.Console;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Reflection;

namespace testProject
{
    // [1] 형식 매개 변수 2개 사용
    class Pair<T, V>
    {
        public T First { get; set; }
        public V Second { get; set; }
        public Pair(T firset, V second)
        {
            First = firset;
            Second = second;
        }
    }

    class Program
    {         
        static void Main(string[] args)
        {
            // [A] string, bool 2개 형식으로 받기
            var my = new Pair<string, bool>("나는 멋져!", true);
            WriteLine($"{my.First} : {my.Second}");

            // [B] int, double 2개 형식으로 받기
            var tuple = new Pair<int, double>(1234, 3.14);
            WriteLine($"{tuple.First} : {tuple.Second}");
        }
    }
}

profile
아직까지는 코린이!

0개의 댓글