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); }
}

'.NET프로그래밍 > C# 3.5 SP1' 카테고리의 다른 글

78. 특성(Attribute)  (0) 2009.08.18
77. 형식매개변수에 대한 제약조건  (0) 2009.08.18
75. 리스트제네릭클래스  (0) 2009.08.17
74. 예외처리  (0) 2009.08.17
73 . 연산자오버로드  (0) 2009.08.17
Posted by holland14
:


==> 리스트제네릭클래스.cs



using System;
using System.Collections.Generic;

public class 리스트제네릭클래스
{
    public static void Main()
    {
        // 정수형
        List<int> su = new List<int>();
        su.Add(10); su.Add(20); su.Add(30);
        for (int i = 0; i < su.Count; i++)
        {
            Console.WriteLine("{0}", su[i]);
        }

        // 문자열
        List<string> str = new List<string>();
        str.Add("안녕"); str.Add("반가워"); str.Add("또봐");
        for (int i = 0; i < str.Count; i++)
        {
            Console.WriteLine("{0}", str[i]);
        }

        // 개체형(테이블형태) : 문자열, 정수
        List<ProductInfo> lstProduct = new List<ProductInfo>();

        ProductInfo pi1 = new ProductInfo(); //[1] 속성 사용
        pi1.ModelName = "TV"; pi1.Quantity = 10;
        lstProduct.Add(pi1);
       
        //ProductInfo pi2 = new ProductInfo();
        //pi2.ModelName = "RADIO"; pi2.Quantity = 5;
        lstProduct.Add(new ProductInfo("RADIO", 5)); //[2] 생성자 사용 ==> 가장 추천하는 방법이다.

       
        //ProductInfo pi3 = new ProductInfo();
        //pi3.ModelName = "DVD"; pi3.Quantity = 3;
        lstProduct.Add(new ProductInfo() { ModelName = "DVD", Quantity = 3 }); //[3] 컬렉션/개체 초기화자

        //lstProduct.Add(pi1);
        //lstProduct.Add(pi2);
        //lstProduct.Add(pi3);

        // 출력 : 윈폼/웹폼에서는 DataSource 개념 적용
        for (int i = 0; i < lstProduct.Count; i++)
        {
            Console.WriteLine("{0}, {1}", lstProduct[i].ModelName, lstProduct[i].Quantity);
        }
    }

}



==============================================================================================



==> Product.cs



using System;

public class ProductInfo
{
    // 상품명
    public string ModelName { get; set; }

    // 판매량
    public int Quantity { get; set; }

    // 생성자
    public ProductInfo()
    {
        // Empty    //  ==> "사용하지 않는다."
    }

    public ProductInfo(string modelName, int quantity)
    {
        this.ModelName = modelName;
        this.Quantity = quantity;
    }

}

'.NET프로그래밍 > C# 3.5 SP1' 카테고리의 다른 글

77. 형식매개변수에 대한 제약조건  (0) 2009.08.18
76. 제네릭클래스  (0) 2009.08.18
74. 예외처리  (0) 2009.08.17
73 . 연산자오버로드  (0) 2009.08.17
72. 변환연산자  (0) 2009.08.17
Posted by holland14
:

// 예외(Exception) : 오류(Error)
// 컴파일(문법) 오류 : 잘못 타이핑, 잘못된 문법이면 Visual Studio가 바로 잡아준다.
//     - 많이 타이핑, 많은 학습을 해야 한다.
// 런타임(실행) 오류 : 실행시 발생,
//     - 많은 테스트를 해봐야 한다.
// 논리(잘못된분석?) 오류 : 잘못된 분석/설계/구현(오탈자) 등등
//     - 많은 프로그램 작성 경험이 필요하다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 예외처리
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 5;
            int b = 0;
            //int c = 5 / 0; // 컴파일에러
            //int c = a / b; // 런타임에러 발생한다.
            int c = a + b; // 논리상 나누기가 필요한데, 더하기(+)를 해버렸다?
            Console.WriteLine("{0}", c);

            ExceptionHandling();
        }

        private static void ExceptionHandling()
        {
            //int a = 5;
            //int b = 0;
            // try에서 예외발생 : [2] [3]번 코드 실행
            // try에서 예외발생하지 않으면 : [3]번만 실행
            try
            {
                //[1] 예외 발생할만한 구문 넣어놓는곳...
                //int c = a / b; // 예외가 발생할만한 구문은 try절에...
                //throw (new Exception("내가 만든 에러")); // 예외를 던지다(발생) ==> throw는 에러를 발생시키는 구문이다.
                DivideByZeroException dbze = new DivideByZeroException("듀글래?");
                throw dbze; 
                // 위의 2줄을 간단히 한줄로 throw new DivideByZeroException("듀글래?");   <== 이렇게 써도 된다.
            }
            catch (Exception ex)
            {
                //[2] 예외가 발생했을 때에만 실행됨
                Console.WriteLine("예외발생 : {0}", ex.Message); // 메시지 출력
            }
            finally
            {
                //[3] 예외가 발생하던 안하던 실행
                Console.WriteLine("프로그램을 정상 종료합니다.");
            }
        }
    }
}

'.NET프로그래밍 > C# 3.5 SP1' 카테고리의 다른 글

76. 제네릭클래스  (0) 2009.08.18
75. 리스트제네릭클래스  (0) 2009.08.17
73 . 연산자오버로드  (0) 2009.08.17
72. 변환연산자  (0) 2009.08.17
71. 반복기(Iterator)  (0) 2009.08.17
Posted by holland14
:


==> 연산자오버로드.cs



using System;

public class 연산자오버로드
{
    public static void Main()
    {
        // int 키워드를 Integer로 모방
        //Integer i = new Integer(10);
        Integer i = 10; // 위 라인 대체
        //Integer j = new Integer(20);
        Integer j = 20;
        //Integer k = new Integer(0);
        Integer k = 0;
        //i.Value++;를 i++;로 줄여쓰고 싶으면 단한연산자 오버로드 코드블록이 있어야 한다.
        i++; // 단항 연산자 오버로드
        --j;

        //k.Value = i.Value + j.Value;
        k = i + j; // 이항 연산자 오버로드
        k = k - i;
        Console.WriteLine(Integer.MaxValue);
        Console.WriteLine(Integer.MinValue);
        //Console.WriteLine(k.Value);
        Console.WriteLine(k); // ToString() 메서드 오버라이드
    }

}

public partial class Integer
{
    // 상수형 필드 : 상수는 반드시 선언 동시 초기화
    public const int MaxValue = int.MaxValue;

    // 읽기전용 필드 :  선언동시초기화 또는 생성자초기화
    public static readonly int MinValue = int.MinValue;

    // 정적생성자를 통해서 읽기전용필드 초기화 가능
    static Integer()
    {
        MinValue = int.MinValue;
    }
}




==============================================================================================



==> Integer.cs



using System;

public partial class Integer
{
    private int value;
    public Integer(int value)
    {
        this.value = value;
    }
    public int Value
    {
        get { return value; }
        set { this.value = value; }
    }

    // 변환연산자
    public static implicit operator Integer(int value)
    {
        return new Integer(value);
    }

    // ToString() 메서드 오버라이드
    public override string ToString()
    {
        return value.ToString(); // 기본 값을 외부에 개체명으로 공개
    }

    // 단항 연산자 오버로드
    public static Integer operator ++(Integer data)
    {
        return ++data.value;
    }

    public static Integer operator --(Integer data)
    {
        return --data.value;
    }


    // 이항 연산자 오버로드
    public static Integer operator +(Integer a, Integer b)
    {
        return (a.value + b.value);
    }

    public static Integer operator -(Integer a, Integer b)
    {
        return (a.value - b.value);
    }
}

'.NET프로그래밍 > C# 3.5 SP1' 카테고리의 다른 글

75. 리스트제네릭클래스  (0) 2009.08.17
74. 예외처리  (0) 2009.08.17
72. 변환연산자  (0) 2009.08.17
71. 반복기(Iterator)  (0) 2009.08.17
70. 암시적으로 형식화된 로컬 변수  (0) 2009.08.17
Posted by holland14
:


==> 변환연산자.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 변환연산자
{
    class Program
    {
        static void Main(string[] args)
        {
            //Car car;
            //car = new Car("에쿠스");
            //Car car = new Car("에쿠스");
            Car car = "에쿠스";

            Console.WriteLine("{0}", car.Name);

            Car myCar = "마이카"; // new Car("마이카");
        }
    }
}




==============================================================================================



==> Car.cs



using System;

public class Car
{
    private string name;
    public Car(string name)
    {
        this.name = name;
    }
    public string Name
    {
        get { return name; }
    }

    //[!] 변환연산자 구현
    public static implicit operator Car(string name)
    {
        // 생성자에게 재 전송
        return new Car(name);
    }
}

'.NET프로그래밍 > C# 3.5 SP1' 카테고리의 다른 글

74. 예외처리  (0) 2009.08.17
73 . 연산자오버로드  (0) 2009.08.17
71. 반복기(Iterator)  (0) 2009.08.17
70. 암시적으로 형식화된 로컬 변수  (0) 2009.08.17
69. 분할클래스(partial class)  (0) 2009.08.17
Posted by holland14
:


==>  반복기.cs



// Iterator : 내가 만든 객체를 foreach문으로
// 돌리고자할 때 반복기가 구현되어있어야 함..

using System;

public class 반복기
{
    public static void Main()
    {
        int[] data = {1, 2, 3 };
        foreach (var item in data)
        {
            Console.WriteLine(item);
        }
        Car hyundai; // Class
        hyundai = new Car(3); // Constructor
        hyundai[0] = "에쿠스"; // Indexer
        hyundai[1] = "제네시스";
        hyundai[2] = "그랜져";
        // Length Property

        for (int i = 0; i < hyundai.Length; i++)
        {
            Console.WriteLine(hyundai[i]);
        }

        // Iterator
        foreach (var item in hyundai)
        {
            Console.WriteLine(item);
        }
    }

}




==============================================================================================



==> Car.cs



using System;

public partial class Car
{
    public int Length { get; set; }
    private string[] names;
    public Car(int length)
    {
        this.Length = length;
        names = new string[length];
    }
    public string this[int index]
    {
        get { return names[index]; }
        set { names[index] = value; }
    }

    // Iterator : 반복기 : GetEnumerator
    public System.Collections.IEnumerator GetEnumerator()
    {
        for (int i = 0; i < names.Length; i++)
        {
            yield return names[i];
        }
    }
}


/*
yield : 나열하다

foreach문은 GetEnumerator함수를 호출한다.

'GetEnumerator()메서드'의 반환값은 'IEnumerator인터페이스'이다.
*/

Posted by holland14
:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 암시적으로형식화된로컬변수
{
    class Program
    {
        static void Main(string[] args)
        {
            // 변수 선언
            int a = 10;
           
            // Nullable 형식
            int? b = null; //
           
            // 암시적으로 형식화된 로컬 변수
            var i = 1234; // 알아서 초기화되는 값으로 선언
            var s = "1234";

            // 타입 출력
            Console.WriteLine("{0}", i.GetType()); // Int32
            Console.WriteLine("{0}", s.GetType()); // String
           
        }
    }
}

Posted by holland14
:


==> 분할클래스.cs



// 분할클래스:
// 동일한 클래스를 여러개의 파일에 걸쳐 나눠서 설계
// 실제 빌드(컴파일)했을 때에는 단일 클래스로 합쳐짐...
using System;

public class 분할클래스
{
    public static void Main()
    {
        Car s = new Car("소나타");
        s.Run();
    }

}

public partial class Car
{
    // Constructor
    public Car(string name)
    {
        this.name = name;
    }
}




==============================================================================================



==> Car.cs



using System;

public partial class Car
{
    // Field
    private string name;
}

public partial class Car
{
    // Method
    public void Run()
    {
        Console.WriteLine("{0} 달리다", this.name);
    }
}

Posted by holland14
:

// 참조타입 관련 연산자
// is 연산자 : str is string : str변수가  string 형식인지 검사 : bool값
// as 연산자 : (str is string) ? str: null;    : is 연산자 + ?: 연산자
// ?? 연산자

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 추가연산자
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 10; // 값형식은 사용 불가

            string s = "안녕";
            object o = s;
            int? num = null; // ?? 연산자는 Nullable

            Console.WriteLine("{0}", (o is string) ); // True
            Console.WriteLine("{0}", (o as string) ); // (o is string) ?  o : null;
            Console.WriteLine("{0}", (num ?? 1234) ); // 의미 -> (num is null) ? 1234 : num;
        }
    }
}

Posted by holland14
:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 값형식과참조형식
{
    class Program
    {
        static void Main(string[] args)
        {
            // 값 형식 : Value Type : 닷넷이 관리하는 메모리의 스택에 보관
            int i = 1234;

            // 참조 형식 : Reference Type : 닷넷의 힙 메모리에 보관
            string s = "안녕\0하세요"; // 리터럴(Literal)
            Console.WriteLine("{0}", s); // "안녕"만 출력된다.

            // 박싱(Boxing)과 언박싱(UnBoxing)
            string su = "1234";
            int num = Convert.ToInt32(su); // 힙 -> 스택 : 언박싱
            su = i.ToString(); // 스택 -> 힙 : Boxing
            su = null; // GC엔진활동

            // 구조체는 값형식, 클래스는 참조형식
            // Car car = new Car(); // 생성
            // car.Run(); // 사용
            // delete car; // 이런 명령어 없다...
        }
    }
}


/*
박싱과 언박싱은 최소로 하는게 좋다.(= 되도록 하지 않는게 좋다.)
속도가 늦어지기 때문이다.
 
\0  =>  종결문자열을 나타낸다.(= 문자열의 끝) 원칙적으로 \0이후의 문자열은 출력되지 않는다.
*/

Posted by holland14
: