.NET프로그래밍/C# 3.5 SP1

76. 제네릭클래스

holland14 2009. 8. 18. 09:21

using System;

public class 제네릭클래스
{
    public static void Main()
    {
        // 기본클래스 메서드 호출
        //Hello h = new Hello();
        //h.SayInt(1234); h.SayStr("안녕"); h.SayObj(DateTime.Now);
        // 제네릭 클래스 호출
        Hello<int> hi = new Hello<int>(); hi.Say(1234);
        Hello<string> hs = new Hello<string>(); hs.Say("안녕");
        Hello<string> say = new Hello<string>("반갑습니다.");
        say.Say(); say.SayType();
    }
}

// 제네릭 클래스 설계
public class Hello<T>
{
    private T msg;
    public Hello() { msg = default(T); } // 생성자
    public Hello(T msg) { this.msg = msg; }
   
    public void Say() { Console.WriteLine("{0}", this.msg); }
    public void Say(T msg) { Console.WriteLine("{0}", msg); }
    public void SayType()
    {
        T temp; temp = default(T); // int이면 0으로, string이면 null로, bool이면 false로 알아서 type에 맞게 초기화 해준다.
        Console.WriteLine("{0}", temp);
    }
    //public void SayInt(int msg) { Console.WriteLine("{0}", msg); }
    //public void SayStr(string msg) { Console.WriteLine("{0}", msg); }
    //public void SayObj(object msg) { Console.WriteLine("{0}", msg); }
}