포스트

(C#) 30. Generic (일반화)

Syntax (문법)

Generic () : Syntax ()

  • 최초 작성일: 2021년 3월 21일(월)

##

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Collections.Generic;

namespace Generic
{
    class Program
    {
        // class MyList<T> where T : struct    // 어떤 T라도 괜찮지만 값 형식이어야한다.
        class MyList<T> //where T : Monster
        {
            T[] arr = new T[10];

            public T GetItem(int i)
            {
                return arr[i];
            }
        }

        class Monster
        {

        }

        static void Test<T>(T input)      // T 자리에 어떤 Type을 넣어도 잘 동작한다.
        {

        }

        static void Main(string[] args)
        {
            //var obj3 = 3;
            //var obj4 = "hello world";     // 자동으로 var를 값에 맞춤.

            // boxing
            //object obj = 3;
            //object obj2 = "hello world";

            //int nubmer = 3;

            // unboxing
            //int num = (int)obj;
            //string str = (string)obj2;

            Test<int>(3);
            Test<float>(3.0f);

            MyList<int> myIntList = new MyList<int>();
            int item = myIntList.GetItem(0);

            MyList<short> myshortList = new MyList<short>();
            MyList<Monster> myMonsterList = new MyList<Monster>();
        }
    }
}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.