전공 과목 이수2👨‍💻/닷넷 c#

💯4~6장💯

천숭이 2020. 11. 3. 16:46
예제 4-15
// p.182 4-15
using System;
class RWOnlyPropertyApp
{
    private int readOnlyField = 100;
    private int writeOnlyField;
    public int ReadOnlyProperty
    {
        get
        {
            Console.WriteLine("In the ReadOnlyProperty ...");
            return readOnlyField;
        }
    }
    public int WriteOnlyProperty
    {
        set
        {
            Console.WriteLine("In the WriteOnlyProperty ...");
            writeOnlyField = value;
        }
    }
    public static void Main()
    {
        RWOnlyPropertyApp obj = new RWOnlyPropertyApp();
        obj.WriteOnlyProperty = obj.ReadOnlyProperty;
        Console.WriteLine("value = " + obj.writeOnlyField);
    }
}

출력:

In the ReadOnlyProperty ...
In the WriteOnlyProperty ...
value = 100

 

예제 4-16
// p.183 4-16
using System;
class PropertyWithoutFieldApp
{
    public string Message
    {
        get { return Console.ReadLine(); }
        set { Console.WriteLine(value);}
    }
    public static void Main()
    {
        PropertyWithoutFieldApp obj = new PropertyWithoutFieldApp();
        obj.Message = obj.Message;
    }
}

입력: Hello

출력: Hello

 

예제 4-17
// p.183 4-17
using System;
class PropertyWithMainFieldsApp
{
    private string text = "Dept. of Computer Engineering";
    private bool isModified = false;
    public string Text
    {
        get { return text; }
        set { text = value; isModified = true; }
    }
    public void PrintStatus()
    {
        Console.WriteLine("text is \"" + text + "\", and " + 
            (isModified ? "is" : "not") + "modified.");
    }
    public static void Main()
    {
        PropertyWithMainFieldsApp obj = new PropertyWithMainFieldsApp();
        obj.PrintStatus();
        obj.Text = "programming language lab";
        obj.PrintStatus();
    }
}

출력:

text is "Dept. of Computer Engineering", and notmodified.
text is "programming language lab", and ismodified.

 

예제 4-18
// p.185 4-18
using System;
class Color
{
    private string[] color = new string[5];
    public string this[int index]
    {
        get { return color[index]; }
        set { color[index] = value; }
    }
}
class IndexerApp
{
    public static void Main()
    {
        Color c = new Color();
        c[0] = "WHITE";
        c[1] = "RED";
        c[2] = "YELLOW";
        c[3] = "BLUE";
        c[4] = "BLACK";
        for(int i = 0; i < 5; i++)
        {
            Console.WriteLine("Color is " + c[i]);
        }
    }
}

출력:

Color is WHITE
Color is RED
Color is YELLOW
Color is BLUE
Color is BLACK

 

예제 4-19
// p.186 4-19
using System;
class StringIndexer
{
    public char this[string str, int index]
    {
        get { return str[index]; }
    }
    public string this[string str, int index, int len]
    {
        get { return str.Substring(index, len); }
    }
}
class STringIndexerApp
{
    public static void Main()
    {
        string str = "Hello";
        StringIndexer s = new StringIndexer();
        for (int i = 0; i < str.Length; i++)
            Console.WriteLine("{0}[{1}] = {2}", str, i, s[str, i]);
        Console.WriteLine("Substring of {0} is {1}", str, s[str, 2, 3]);
    }
}

출력:

Hello[0] = H
Hello[1] = e
Hello[2] = l
Hello[3] = l
Hello[4] = o
Substring of Hello is llo

 

예제 4-20
using System;

namespace Exercise_4_20
{
    delegate void DelegateOne();
    delegate void DelegateTwo(int i);
    class DelegateClass
    {
        public void MethodA()
        {
            Console.WriteLine("In The DelegateClass.MethodA...");
        }
        public void MethodB(int i)
        {
            Console.WriteLine("DelegateClass.MethodB, i= " + i);
        }
    }
    class DelegateCallApp
    {
        public static void Main()
        {
            DelegateClass obj = new DelegateClass();  // 객체 생성

            // 메소드 연결
            DelegateOne d1 = new DelegateOne(obj.MethodA);
            DelegateTwo d2 = new DelegateTwo(obj.MethodB);

            // 메소드 호출
            d1();
            d2(10);
        }
    }
}

출력:

In the DelegateClass.MethodA ...
DelegateClass.MethodB, i= 10

 

예제 4-21
// p.190 4-21
using System;
using System.Security.Cryptography.X509Certificates;

delegate void MultiCastDelegate();
class Schedule
{
    public void Now()
    {
        Console.WriteLine("Time : " + DateTime.Now.ToString());
    }
    public static void Today()
    {
        Console.WriteLine("Date : " + DateTime.Today.ToString());
    }
}
class MultiCastApp
{
    public static void Main()
    {
        Schedule obj = new Schedule();
        MultiCastDelegate mcd = new MultiCastDelegate(obj.Now);
        mcd += new MultiCastDelegate(Schedule.Today);
        mcd();
    }
}

출력:

Time : 2020-11-03 오후 5:48:29
Date : 2020-11-03 오전 12:00:00

 

예제 4-22 DelegateOperationApp.cs
using System;

namespace Exercise_4_22
{
    delegate void MultiDelegate();
    class DelegateClass
    {
        public void MethodA()
        {
            Console.WriteLine("In the DelegateClass.MethodA ... ");
        }
        public void MethodB()
        {
            Console.WriteLine("In the DelegateClass.MethodB ...");
        }
        public void MethodC()
        {
            Console.WriteLine("In the DelegateClass.MethodC ...");
        }
    }
    class DelegateOperation
    {
        public static void Main()
        {
            DelegateClass obj = new DelegateClass();
            MultiDelegate dg1, dg2, dg3;
            dg1 = new MultiDelegate(obj.MethodA);
            dg2 = new MultiDelegate(obj.MethodB);
            dg3 = new MultiDelegate(obj.MethodC);
            // ...
            dg1 = dg1 + dg2;
            dg1 += dg3;
            dg2 = dg1 - dg2;
            dg1();
            Console.WriteLine("After dg1 call ...");
            dg2();
            Console.WriteLine("After dg2 call ..."); ;
            dg3();
        }
    }
}

출력 :

In the DelegateClass.MethodA ...
In the DelegateClass.MethodB ...
In the DelegateClass.MethodC ...
After dg1 call ...
In the DelegateClass.MethodA ...
In the DelegateClass.MethodC ...
After dg2 call ...
In the DelegateClass.MethodC ...

 

예제 4-23 EventHandlingApp.cs
using System;

namespace EventHandlingApp
{
    public delegate void MyEventHandler();
    class Button
    {
        public event MyEventHandler Push;
        public void OnPush()
        {
            if (Push != null)
                Push();
        }
    }
    class EventHandlerClass
    {
        public void MyMethod()
        {
            Console.WriteLine("In The EventHandlerClass.MyMethod ...");
        }
    }
    class EventHanlingApp
    {
        public static void Main()
        {
            Button button = new Button();
            EventHandlerClass obj = new EventHandlerClass();
            button.Push += new MyEventHandler(obj.MyMethod);
            button.OnPush();
        }
    }
}

 

// 예제 4.24 OperatorOverloadingApp.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OperatorOverloadingApp
{
    class Complex
    {
        private double realPart;              // 실수부
        private double imagePart;             // 허수부
        public Complex(double rVal, double iVal)
        {
            realPart = rVal;
            imagePart = iVal;
        }
        public static Complex operator +(Complex x1, Complex x2)
        {
            Complex x = new Complex(0, 0);
            x.realPart = x1.realPart + x2.realPart;
            x.imagePart = x1.imagePart + x2.imagePart;
            return x;
        }
        override public string ToString()
        {
            return "(" + realPart + "," + imagePart + "i)";
        }
    }
    class Program
    {
        public static void Main()
        {
            Complex c, c1, c2;
            c1 = new Complex(1, 2);
            c2 = new Complex(3, 4);
            c = c1 + c2;
            Console.WriteLine(c1 + " + " + c2 + " = " + c);
        }
    }
}
예제 4.25
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// 예제 4.25
namespace XBoolApp
{
    class XBool
    {
        public bool b;
        // XBool 형을 bool 형으로 명시적으로 변환하는 연산자 중복
        public static explicit operator bool(XBool x)
        {
            Console.WriteLine("In the explicit operator bool ...");
            return x.b;
        }
        // XBool 형에 대한 true 연산자의 중복
        public static bool operator true(XBool x)
        {
            Console.WriteLine("In the operator true ...");
            return x.b ? true : false;
        }
        // XBool  형에 대한 false 연산자의 중복
        public static bool operator false(XBool x)
        {
            Console.WriteLine("In the operator false ...");
            return x.b ? false : true;
        }
    }
    class Program
    {
        public static void Main()
        {
            XBool xb = new XBool();
            xb.b = false;
            if (xb)                      // invoke operator true
                Console.WriteLine("True");
            else
                Console.WriteLine("False");
            Console.WriteLine((bool)xb); // invoke conversion-operator bool
        }
    }
}

출력:

In the operator true ...
False
In the explicit operator bool ...
False

 

예제 4.26
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UserDefinedTypeConversionApp
{
    class Mile
    {
        public double distance;
        public Mile(double distance)
        {
            this.distance = distance;
        }
        // Mile operator: double to Mile
        public static implicit operator Mile(double d)
        {
            Mile m = new Mile(d);
            return m;
        }
        // Kilometer operator: Mile to Kilometer
        public static explicit operator Kilometer(Mile m)
        {
            return m.distance * 1.609;
        }
    }
    class Kilometer
    {
        public double distance;
        public Kilometer(double distance)
        {
            this.distance = distance;
        }
        // Kilometer operator: double to Kilo
        public static implicit operator Kilometer(double d)
        {
            Kilometer k = new Kilometer(d);
            return k;
        }
        // Mile operator: Kilo to Mile
        public static explicit operator Mile(Kilometer k)
        {
            return k.distance / 1.609;
        }
    }
    class Program
    {
        public static void Main()
        {
            Kilometer k = new Kilometer(100.0);
            Mile m;
            
            m = (Mile)k;
            Console.WriteLine("{0} km = {1} mile", k.distance, m.distance);

            m = 65.0;
            k = (Kilometer)m;
            Console.WriteLine("{0} mile = {1} km", m.distance, k.distance);
        }
    }
}

출력:

In the operator true ...
False
In the explicit operator bool ...
False

 

예제 4.27
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StructApp
{
    struct Point
    {
        public int x, y;                      // x, y 좌표
        public Point(int x, int y)
        {          // 생성자
            this.x = x;
            this.y = y;
        }
        override public string ToString()
        {   // 메소드
            return "(" + x + ", " + y + ")";
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Point[] pts = new Point[3];
            pts[0] = new Point(100, 100);
            pts[1] = new Point(100, 200);
            pts[2] = new Point(200, 100);
            foreach (Point pt in pts)
                Console.WriteLine(pt.ToString());
        }
    }
}

출력:

(100, 100)
(100, 200)
(200, 100)

 

<5장예제>

예제 5.2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DerivedConstructorApp
{
    class BaseClass
    {
        public BaseClass()
        {
            Console.WriteLine("BaseClass Constructor ...");  // 첫번째로 실행
        }
    }
    class DerivedClass : BaseClass
    {
        public DerivedClass()
        {
            Console.WriteLine("DerivedClass Constructor ...");  // 두번째로 실행
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            DerivedClass obj = new DerivedClass();
            Console.WriteLine("In the main ...");  // 마지막으로 실행(제일 마지막으로 상속된클래스이므로)
        }
    }
}

출력:

BaseClass Constructor ...
DerivedClass Constructor ...
In the main ...

 

 

 

 

4장 레포트 

문제4.13 stack스택 클래스, push, pop메소드, 삽입과 제거가 일어나는 자료구조
using Report4_13;
using System;
using System.ComponentModel.DataAnnotations;

namespace Report4_13
{
    class Stack
    {
        private int[] stack;
        int sp = -1;

        // (1) 스택의 크기가 100인 디폴트 생정자
       public Stack()
        {
            stack = new int[100];
        }
        public Stack(int size)
        {
            stack = new int[size];
        }

        // (2) Push 메소드
        public void Push(int data)
        {
            stack[++sp] = data;
        }

        // (2) Pop 메소드
        public int Pop()
        {
            return stack[sp--];
        }
    }

}

// (3) 클래스 Stack을 이용해 일련의 정수 입력을 역순으로
// 출력하는 테스트 메소드
class Test_Stack
{
    static void Main(string[] args)
    {
        Stack s1 = new Stack();
        string input = Console.ReadLine();
        string[] input_arr = input.Split(' ');
        int[] int_arr = new int[input_arr.Length];

        for(int i = 0; i < input_arr.Length; i++)
        {
            int_arr[i] = int.Parse(input_arr[i]);
        }
        for(int i=0;i<int_arr.Length;i++)
        {
            s1.Push(int_arr[i]);
        }
        
        for(int i = 0; i < int_arr.Length; i++)
        {
            Console.WriteLine(s1.Pop());
        }

    }
}

5장실습

예제5.3
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaseCallApp
{
    class BaseClass
    {
        public int a, b;
        public BaseClass()
        {
            a = 1; b = 1;
        }
        public BaseClass(int a, int b)
        {
            this.a = a; this.b = b;
        }
    }
    class DerivedClass : BaseClass
    {
        public int c;
        public DerivedClass()
        {
            c = 1;
        }
        public DerivedClass(int a, int b, int c)
            : base(a, b)
        {
            this.c = c;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            DerivedClass obj1 = new DerivedClass();
            DerivedClass obj2 = new DerivedClass(1, 2, 3);
            Console.WriteLine("a = {0}, b = {1}, c = {2}",
                obj1.a, obj1.b, obj1.c);
            Console.WriteLine("a = {0}, b = {1}, c = {2}",
                obj2.a, obj2.b, obj2.c);
        }
    }
}

출력:

a = 1, b = 1, c = 1
a = 1, b = 2, c = 3

 

예제 5.4 (메소드재정의)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OverridingAndOverloadingApp
{
    class BaseClass
    {
        public void MethodA()
        {
            Console.WriteLine("In the BaseClass ...");
        }
    }
    class DerivedClass : BaseClass
    {
        new public void MethodA()
        {             // Overriding
            Console.WriteLine("In DerivedClass ... Overriding !!!");
        }
        public void MethodA(int i)
        {           // Overloading
            Console.WriteLine("In DerivedClass ... Overloading !!!");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            BaseClass obj1 = new BaseClass();
            DerivedClass obj2 = new DerivedClass();
            obj1.MethodA();
            obj2.MethodA();
            obj2.MethodA(1);
        }
    }
}

출력:

In the BaseClass ...
In DerivedClass ... Overriding !!!
In DerivedClass ... Overloading !!!

예제 5.5 (가상메소드 버츄얼메소드)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VirtualMethodApp
{
    class BaseClass
    {
        virtual public void MethodA()
        {
            Console.WriteLine("Base MethodA");
        }
        virtual public void MethodB()
        {
            Console.WriteLine("Base MethodB");
        }
        virtual public void MethodC()
        {
            Console.WriteLine("Base MethodC");
        }
    }
    class DerivedClass : BaseClass
    {
        new public void MethodA()
        {
            Console.WriteLine("Derived MethodA");
        }
        override public void MethodB()
        {
            Console.WriteLine("Derived MethodB");
        }
        public void MethodC()
        {
            Console.WriteLine("Derived MethodC");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            BaseClass s = new DerivedClass();
            s.MethodA();
            s.MethodB();
            s.MethodC();
        }
    }
}

출력:

Base MethodA
Derived MethodB
Base MethodC

 

예제5.6 (추상클래스) 선언만하고 상속된 후에 구현되어야 한다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AbstractClassApp
{
    abstract class AbstractClass
    {
        public abstract void MethodA();
        public void MethodB()
        {
            Console.WriteLine("Implementation of MethodB()");
        }
    }
    class ImpClass : AbstractClass
    {
        override public void MethodA()
        {
            Console.WriteLine("Implementation of MethodA()");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ImpClass obj = new ImpClass();
            obj.MethodA();
            obj.MethodB();
        }
    }
}

출력:

Implementation of MethodA()
Implementation of MethodB()

 

예제 5.7
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AddendumApp
{
    class BaseClass
    {
        public void MethodA()
        {
            Console.WriteLine("do BaseClass Task.");
        }
    }
    class DerivedClass : BaseClass
    {
        new public void MethodA()
        {
            base.MethodA();
            Console.WriteLine("do DerivedClass Task.");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            DerivedClass obj = new DerivedClass();
            obj.MethodA();
        }
    }
}

출력:

do BaseClass Task.
do DerivedClass Task.

 

예제 5.9 (다형성)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PolymorphismApp
{
    class BaseClass
    {
        public virtual void Output()
        {
            Console.WriteLine("In the Base class ...");
        }
    }
    class DerivedClass : BaseClass
    {
        public override void Output()
        {
            Console.WriteLine("In the Derived class ...");
        }
    }
    class Program
    {
        static void Print(BaseClass obj)
        {
            obj.Output();
        }
        static void Main(string[] args)
        {
            BaseClass obj1 = new BaseClass();
            DerivedClass obj2 = new DerivedClass();
            Print(obj1);
            Print(obj2);
        }
    }
}


출력:

In the Base class ...
In the Derived class ...

 

예제 5.10 (버츄얼과 오버라이드)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VirtualAndOverrideApp
{
    class CLanguage
    {
        virtual public void Print()
        {
            Console.WriteLine("In the Clanguage class ...");
        }
    }
    class Java : CLanguage
    {
       override public void Print()
        {
            Console.WriteLine("In the Java class ...");
        }
     // override가 아니라 new로 작성될 시 출력은 "In the Clanguage class..."
     // override를 사용하면 같은이름 함수 한개, 
     // new를 사용하면 Print함수종류 두개.(동음이의)
    }
    class Program
    {
        static void Main(string[] args)
        {
            CLanguage c = new Java();
            c.Print();
        }
    }
}

ㅊ:

In the Java class ...

 

예제5.11
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ImplementingInterfaceApp
{
    interface IRectangle
    {
        void Area(int width, int height);
    }
    interface ITriangle
    {
        void Area(int width, int height);
    }
    class Shape : IRectangle, ITriangle
    {
        void IRectangle.Area(int width, int height)
        {
            Console.WriteLine("Rectangle Area : " + width * height);
        }
        void ITriangle.Area(int width, int height)
        {
            Console.WriteLine("Triangle Area : " + width * height / 2);
        }
    }
    class Program
    {
        public static void Main()
        {
            Shape s = new Shape();
            // s.Area(10, 10);             // error - ambiguous !!!
            // s.IRectangle.Area(10, 10);  // error
            // s.ITriangle.Area(10, 10);   // error
            ((IRectangle)s).Area(20, 20);  // 캐스팅-업
            ((ITriangle)s).Area(20, 20);   // 캐스팅-업
            IRectangle r = s;              // 인터페이스로 캐스팅-업
            ITriangle t = s;               // 인터페이스로 캐스팅-업
            r.Area(30, 30);
            t.Area(30, 30);
        }
    }
}

출력:

Rectangle Area : 400
Triangle Area : 200
Rectangle Area : 900
Triangle Area : 450

 

예제 5.12 (다중상속)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DiamondApp
{
    interface IX { void XMethod(int i); }
    interface IY : IX { void YMethod(int i); }
    class A : IX
    {
        private int a;
        public int PropertyA
        {
            get { return a; }
            set { a = value; }
        }
        public void XMethod(int i) { a = i; }
    }
    class B : A, IY
    {
        private int b;
        public int PropertyB
        {
            get { return b; }
            set { b = value; }
        }
        public void YMethod(int i) { b = i; }
    }
    class Program
    {
        public static void Main()
        {
            B obj = new B();
            obj.XMethod(5); obj.YMethod(10);
            Console.WriteLine("a = {0}, b = {1}",
                obj.PropertyA, obj.PropertyB);
        }
    }
}

출력:

a = 5, b = 10

 

예제 5.13 (배열에 원소를 삽입하고 출력하는 구조체)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StructImpApp
{
    interface IVector
    {
        void Insert(int n);    // 배열에 원소를 삽입한다.
        void ScalarSum(int n); // 배열에 각 원소에 스칼라 값을 더한다.
        void PrintVector();    // 배열에 있는 모든 원소를 출력한다.
    }
    struct Vector : IVector
    {
        private int[] v;
        private int index, size;
        public Vector(int size)
        {  // »ý¼ºÀÚ
            v = new int[size];
            this.size = size;
            index = 0;
        }
        public void Insert(int n)
        {
            if (index >= size)
                Console.WriteLine("Error : array overflow");
            else v[index++] = n;
        }
        public void ScalarSum(int n)
        {
            for (int i = 0; i < index; i++) v[i] += n;
        }
        public void PrintVector()
        {
            Console.Write("Contents:");
            for (int i = 0; i < index; i++)
                Console.Write(" " + v[i]);
            Console.WriteLine();
        }
    }
    class Program
    {
        public static void Main()
        {
            Vector a = new Vector(100);
            int n;
            while (true)
            {         // 0이 입력될 때까지 반복한다.
                n = Console.Read() - '0';
                if (n == 0) break;
                a.Insert(n);
            }
            a.PrintVector();
            a.ScalarSum(10);
            a.PrintVector();
        }
    }
}

입력 : 123450

출력:

Contents: 1 2 3 4 5
Contents: 11 12 13 14 15

 

<5장 연습문제>

[과제]연습문제5.8 (추상클래스로 사각형과 원에 대해 작성)
using Exercise_5_8;
using System;

namespace Exercise_5_8
{
    abstract class Figure
    {
        public abstract void Area();
        public abstract void Girth();
        public abstract void Draw();
    }
    class Circle : Figure
    {
        protected int radius = 50;
        public Circle(int radius)
        {
            this.radius = radius;
        }
        override public void Area()  // 원의 넓이
        {
            Console.WriteLine("원의 넓이 : " + Math.PI * radius * radius);
        } 
        override public void Girth()
        {
            Console.WriteLine("원의 둘레 : " + Math.PI * 2 * radius);
        }
        override public void Draw()
        {
            int i, j;

            for(i =0;i<radius;i++)
            {
                for(j=0;j<radius;j++)
                {
                    if((i+0.5-radius/2.0) * (i+0.5-radius/2.0) + (j+0.5-radius/2.0)
                        * (j+0.5-radius/2.0) < radius*radius/4.0)
                    {
                        Console.Write("* ");
                    }
                    else
                    {
                        Console.Write("  ");
                    }
                }
                Console.WriteLine();
            }
        }
    }

    class Rectangle : Figure
    {
        protected int a, b;
        public Rectangle()
        {
            a = 1;
            b = 1;
        }
        public Rectangle(int a,int b)
        {
            this.a = a;
            this.b = b;
        }
        override public void Area()
        {
            Console.WriteLine("사각형의 넓이 : " + a*b);
        }
        override public void Girth()
        {
            Console.WriteLine("사각형의 둘레 : " + 2 * a + 2 * b);
        }
        override public void Draw()
        {
            for (int i = 0; i <= a; i++)
            {
                Console.Write("* ");
            }
            Console.WriteLine("");
            for(int i = 0; i < b; i++)
            {
                Console.Write("*");
                for(int j=1;j<a;j++)
                {
                    Console.Write("  ");
                }
                Console.WriteLine(" *");
            }
            for (int i = 0; i <= a; i++)
            {
                Console.Write("* ");
            }
            Console.WriteLine("");
        }
    }
    
    class Shape
    {
        public static void Main()
        {

            Circle c = new Circle(13);
            c.Area();
            c.Girth();
            c.Draw();

            Console.WriteLine();

            Rectangle r = new Rectangle(17, 5);
            r.Area();
            r.Girth();
            r.Draw();
        }
    }
}

원의 넓이 : 530.929158456675
원의 둘레 : 81.68140899333463
        * * * * *
    * * * * * * * * *
  * * * * * * * * * * *
  * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * *
  * * * * * * * * * * *
  * * * * * * * * * * *
    * * * * * * * * *
        * * * * *

사각형의 넓이 : 85
사각형의 둘레 : 3410
* * * * * * * * * * * * * * * * * *
*                                 *
*                                 *
*                                 *
*                                 *
*                                 *
* * * * * * * * * * * * * * * * * *

 

[과제] 연습문제5.9 (문장입력받고 스택,큐형식으로 알맞게 출력)
using Exercise_5_9;
using System;

namespace Exercise_5_9
{
    interface IOperation
    {
        void Insert(string str);
        string Delete();
        bool Search(string str);
        string GetCurrentElt();
        int NumOfElements();
    }

    class Stack : IOperation
    {
        private string[] stack;
        int sp = -1;

        public Stack()
        {
            stack = new string[10];
        }
        public Stack(int size)
        {
            stack = new string[size];
        }

        // (1) - 1
        void IOperation.Insert(string str)
        {
            stack[++sp] = str;
        }
        // (1) - 2
        string IOperation.Delete()
        {
            return stack[sp--];
        }
        // (1) - 3
        bool IOperation.Search(string str)
        {
            int i;
            for (i = 0; i <= sp; i++)
            {
                if (str == stack[i]) break;
            }
            if (i <= sp) return true;
            return false;
        }
        // (1) - 4
        string IOperation.GetCurrentElt()
        {
            return stack[sp];
        }
        // (1) - 5
        int IOperation.NumOfElements()
        {
            return sp+1;
        }
    }

    // 5.9 2번 Queue클래스
    // 삭제가일어나는곳은 front, 삽입이 일어나는 곳이 rear
    // 선입선출
    class Queue : IOperation
    {
        private string[] stack;
        int rear = -1;
        int front = 0;

        public Queue()
        {
            stack = new string[10];
        }
        public Queue(int size)
        {
            stack = new string[size];
        }

        // (2) - 1
        void IOperation.Insert(string str)
        {
            stack[++rear] = str;
        }
        // (2) - 2
        string IOperation.Delete()
        {
            return stack[front++];
        }
        // (2) - 3
        bool IOperation.Search(string str)
        {
            int i;
            for (i = front; i <= rear; i++)
            {
                if (str == stack[i]) break;
            }
            if (i <= rear) return true;
            else return false;
        }
        // (2) - 4
        string IOperation.GetCurrentElt()
        {
            return stack[front];
        }
        // (2) - 5
        int IOperation.NumOfElements()
        {
            return rear+1;
        }
    }

    // 스택과 큐를 테스트하는 클래스
    class Test
    {
        public static void Main(string[] args)
        {
            // Stack 클래스 테스트
            Console.WriteLine("\t < Stack> ");
            Stack s1 = new Stack(50);
            string input = Console.ReadLine();
            string[] input_arr = input.Split(' ');

            for(int i=0;i<input_arr.Length;i++)
            {
                ((IOperation)s1).Insert(input_arr[i]);
            }
            string Search_ele;
            Console.Write("검색하고 싶은 원소를 입력하시오 : ");
            Search_ele = Console.ReadLine();
            Console.WriteLine("Search() \t: "+((IOperation)s1).Search(Search_ele));
            Console.WriteLine("GetCurrentElt()  : "+((IOperation)s1).GetCurrentElt());
            Console.WriteLine("NumOfElements()  : "+((IOperation)s1).NumOfElements());

            Console.Write("모든 원소 Delete() : ");
            for(int j=0;j<input_arr.Length;j++)
            {
                Console.Write(((IOperation)s1).Delete()+" ");
            }
            Console.WriteLine();
            Console.WriteLine();
            // Queue 클래스 테스트
            Console.WriteLine("\t < Queue> ");
            Queue q1 = new Queue(50);
            string input2 = Console.ReadLine();
            string[] input_arr2 = input2.Split(' ');

            for (int i = 0; i < input_arr2.Length; i++)
            {
                ((IOperation)q1).Insert(input_arr2[i]);
            }
            string Search_q;
            Console.Write("검색하고 싶은 원소를 입력하시오 : ");
            Search_q = Console.ReadLine();
            Console.WriteLine("Search() \t: " + ((IOperation)q1).Search(Search_q));
            Console.WriteLine("GetCurrentElt()  : " + ((IOperation)q1).GetCurrentElt());
            Console.WriteLine("NumOfElements()  : " + ((IOperation)q1).NumOfElements());

            Console.Write("모든 원소 Delete() : ");
            for (int j = 0; j < input_arr.Length; j++)
            {
                Console.Write(((IOperation)q1).Delete() + " ");
            }
        }
    }
}

         < Stack>
내일 공수, 닷넷 시험 실화냐1!!!!
검색하고 싶은 원소를 입력하시오 : 시험
Search()        : True
GetCurrentElt()  : 실화냐1!!!!
NumOfElements()  : 5
모든 원소 Delete() : 실화냐1!!!! 시험 닷넷 공수, 내일

         < Queue>
얼른 공부하자 천숭아 화이팅 ㅎㅅㅎ
검색하고 싶은 원소를 입력하시오 : ㅎㅅㅎ
Search()        : True
GetCurrentElt()  : 얼른
NumOfElements()  : 5
모든 원소 Delete() : 얼른 공부하자 천숭아 화이팅 ㅎㅅㅎ

 

[과제]연습문제 5.11 (인터페이스로 사각형, 원 넓이둘레그리기 메소드 작성)
using System;
using Report_5_11;

namespace Report_5_11
{
    public interface IFigure
    {
        void Area();
        void Girth();
        void Draw();
    }

    class Circle : IFigure
    {
        protected int radius;
        public Circle()
        {
            this.radius = 10;
        }
        public Circle(int size)
        {
            radius = size;
        }

        void IFigure.Area()
        {
            Console.WriteLine("원의 넓이 : " + Math.PI * radius * radius);
        }
        void IFigure.Girth()
        {
            Console.WriteLine("원의 둘레 : " + Math.PI * 2 * radius);
        }
        void IFigure.Draw()
        {
            int i, j;
            for (i = 0; i < radius; i++)
            {
                for (j = 0; j < radius; j++)
                {
                    if ((i + 0.5 - radius / 2.0) * (i + 0.5 - radius / 2.0) + (j + 0.5 - radius / 2.0)
                        * (j + 0.5 - radius / 2.0) < radius * radius / 4.0)
                    {
                        Console.Write("* ");
                    }
                    else
                    {
                        Console.Write("  ");
                    }
                }
                Console.WriteLine();
            }
        }
    }

    class Rectangle : IFigure
    {
        protected int a, b;
        public Rectangle()
        {
            a = 1;
            b = 1;
        }
        public Rectangle(int a, int b)
        {
            this.a = a;
            this.b = b;
        }

        void IFigure.Area()
        {
            Console.WriteLine("사각형의 넓이 : " + a * b);
        }
        void IFigure.Girth()
        {
            Console.WriteLine("사각형의 둘레 : " + 2 * a + 2 * b);
        }
        void IFigure.Draw()
        {
            for (int i = 0; i <= a; i++)
            {
                Console.Write("* ");
            }
            Console.WriteLine("");
            for (int i = 0; i < b; i++)
            {
                Console.Write("*");
                for (int j = 1; j < a; j++)
                {
                    Console.Write("  ");
                }
                Console.WriteLine(" *");
            }
            for (int i = 0; i <= a; i++)
            {
                Console.Write("* ");
            }
            Console.WriteLine("");
        }
    }
    class Shape
    {
        public static void Main()
        {
            Circle c = new Circle(10);
            ((IFigure)c).Area();
            ((IFigure)c).Girth();
            ((IFigure)c).Draw();

            Console.WriteLine();

            Rectangle r = new Rectangle(10, 10);
            ((IFigure)r).Area();
            ((IFigure)r).Girth();
            ((IFigure)r).Draw();
        }
    }
}

원의 넓이 : 314.1592653589793
원의 둘레 : 62.83185307179586
      * * * *
  * * * * * * * *
  * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
  * * * * * * * *
  * * * * * * * *
      * * * *

사각형의 넓이 : 100
사각형의 둘레 : 2020
* * * * * * * * * * *
*                   *
*                   *
*                   *
*                   *
*                   *
*                   *
*                   *
*                   *
*                   *
*                   *
* * * * * * * * * * *

 

6장실습

 

< 6장 제네릭 >

예제 6.1 (제네릭클래스의 아주 기본적인 형태:정수,실수 제네릭클래스 만들어서 출력)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GenericClassApp
{
    class SimpleGeneric<T>
    {
        private T[] values;
        private int index;

        public SimpleGeneric(int len)
        { // Constructor
            values = new T[len];
            index = 0;
        }

        public void add(params T[] args)
        {
            foreach (T e in args)
                values[index++] = e;
        }

        public void print()
        {
            foreach (T e in values)
                Console.Write(e + " ");
            Console.WriteLine();
        }
    }

    public class Program
    {
        public static void Main()
        {
            SimpleGeneric<Int32> gInteger = new SimpleGeneric<Int32>(10);
            SimpleGeneric<Double> gDouble = new SimpleGeneric<Double>(10);

            gInteger.add(1, 2);
            gInteger.add(1, 2, 3, 4, 5, 6, 7);
            gInteger.add(0);
            gInteger.print();

            gDouble.add(10.1, 20.2, 30.3);
            gDouble.print();
        }
    }
}

출력:

1 2 1 2 3 4 5 6 7 0
10.1 20.2 30.3 0 0 0 0 0 0 0

 

예제6.2 (제네릭 인터페이스)

제네릭 클래스를 사용해 입력한 값들의 형식을 출력하는 과정

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

namespace GenericInterfaceApp
{
    interface IGenericInterface<T>
    {
        void setValue(T x);
        string getValueType();
    }

    class GenericClass<T> : IGenericInterface<T> {
        private T value;
        public void setValue(T x) {
            value = x;
        }

        public string getValueType() {
            return value.GetType().ToString();
        }
    }

    public class Program
    {
        public static void Main()
        {
            GenericClass<Int32> gInteger = new GenericClass<Int32>();
            GenericClass<String> gString = new GenericClass<String>();

            gInteger.setValue(10);
            gString.setValue("Text");

            Console.WriteLine(gInteger.getValueType());
            Console.WriteLine(gString.getValueType());
        }
    }
}

출력 :

System.Int32

System.String

 

예제 6.3 (swap)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GenericMethodApp
{
    class Program
    {
        static void Swap<DataType>(ref DataType x, ref DataType y) 
        {
            DataType temp;
            temp = x; 
		    x = y; 
		    y = temp;
        }
        static void Main(string[] args)
        {
            int a = 1, b = 2; double c = 1.5, d = 2.5;
            Console.WriteLine("Before: a = {0}, b = {1}", a, b);
            Swap<int>(ref a, ref b);                                // 정수형 변수로 호출
            Console.WriteLine(" After: a = {0}, b = {1}", a, b);
            Console.WriteLine("Before: c = {0}, d = {1}", c, d);
            Swap<double>(ref c, ref d);                             // 실수형 변수로 호출
            Console.WriteLine(" After: c = {0}, d = {1}", c, d);
        }
    }
}

출력 :

Before: a = 1, b = 2
 After: a = 2, b = 1
Before: c = 1.5, d = 2.5
 After: c = 2.5, d = 1.5

 

예제6.4(제한된 형 매개변수)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BoundedGenericApp
{
    class GenericType<T> where T : SystemException
    {
        private T value;

        public GenericType(T v)
        {
            value = v;
        }

        override public String ToString()
        {
            return "Type is " + value.GetType();
        }
    }

    public class Program
    {
        public static void Main()
        {
            GenericType<NullReferenceException> gNullEx = new GenericType<NullReferenceException>(new NullReferenceException());
            GenericType<IndexOutOfRangeException> gIndexEx = new GenericType<IndexOutOfRangeException>(new IndexOutOfRangeException());
            // GenericType<String> gString = new GenericType<String>("Error"); //에러

            Console.WriteLine(gNullEx.ToString());
            Console.WriteLine(gIndexEx.ToString());
        }
    }
}

c출력:

Type is System.NullReferenceException
Type is System.IndexOutOfRangeException

 

예제 6.13 (예외 발생)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UserHandlerApp
{
    class UserExceptionOne : ApplicationException { }
    class UserExceptionTwo : ApplicationException { }
    class Program
    {
        static void Method(int i)
        {
            if (i == 1) throw new UserExceptionOne();
            else throw new UserExceptionTwo();
        }
        public static void Main()
        {
            try
            {
                Console.WriteLine("Here: 1");
                Method(2);
                Console.WriteLine("Here: 2");
            }
            catch (UserExceptionOne)
            {
                Console.WriteLine("UserExceptionOne is occurred!!!");
            }
            catch (UserExceptionTwo)
            {
                Console.WriteLine("UserExceptionTwo is occurred!!!");
            }
            Console.WriteLine("Here: 3");
        }
    }
}

출력:

Here: 1
UserExceptionTwo is occurred!!!
Here: 3

 

 

(나머지 예외는 책, ppt보고 공부하기)

 

<스레드 프로그래밍>

ThreadStart ts = new ThreadStart(ThreadBody);  
Thread t = new Thread(ts);                 

-> 위 두줄을 한줄로 작성    

Thread t = new Thread(new ThreadStart(ThreadBody));

예제 6.18 (스레드를 생성하고 실행시키는 기본 예제)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace SimpleThreadApp
{
    class Program
    {
        static void ThreadBody()                            // --- 1
        {                       
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(DateTime.Now.Second + " : " + i);
                Thread.Sleep(1000);
            }
        }
        public static void Main()
        {
            ThreadStart ts = new ThreadStart(ThreadBody);   // --- 2
            Thread t = new Thread(ts);                      // --- 3
            Console.WriteLine("*** Start of Main");
            t.Start();                                      // --- 4
            Console.WriteLine("*** End of Main");
        }
    }
}

출력:

(컴퓨터마다 출력이 조금씩 다름)

 

예제 6.19 (현재실행되는스레드의 정보를 스레드 함수 이용해 출력)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ThreadPropertyApp
{
    class ThreadProperty
    {
        public void ThreadBody()
        {
            Thread myself = Thread.CurrentThread;
            for (int i = 1; i <= 3; i++)
            {
                Console.WriteLine("{0} is activated => {1}",
                    myself.Name, i);
                Thread.Sleep(1000);
            }
        }
    }
    class Program
    {
        public static void Main()
        {
            ThreadProperty obj = new ThreadProperty();
            ThreadStart ts = new ThreadStart(obj.ThreadBody);
            Thread t1 = new Thread(ts);
            Thread t2 = new Thread(ts);
            t1.Name = "Apple"; t2.Name = "Orange";
            t1.Start(); t2.Start();
        }
    }
}

Apple is activated => 1
Orange is activated => 1
Apple is activated => 2
Orange is activated => 2
Apple is activated => 3
Orange is activated => 3

 

예제 6.20 스레드메소드로 스레드 상태 변경
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ThreadStateApp
{
    class ThreadState
    {
        public void ThreadBody()
        {
            while (true)
            {
                // ... infinite loop ...
            }
        }
    }
    class Program
    {
        public static void Main()
        {
            ThreadState obj = new ThreadState();
            ThreadStart ts = new ThreadStart(obj.ThreadBody);
            Thread t = new Thread(ts);
            Console.WriteLine("Step 1: " + t.ThreadState);
            t.Start();  // 스레드 실행
            Thread.Sleep(100);
            Console.WriteLine("Step 2: " + t.ThreadState);
            t.Suspend(); // 스레드를 대기상태로
            Thread.Sleep(100); // 0.1초동안 멈추기
            Console.WriteLine("Step 3: " + t.ThreadState);
            t.Resume(); // 대기상태 스레드를 실행상태로
            Thread.Sleep(100);
            Console.WriteLine("Step 4: " + t.ThreadState);
            t.Abort();  // 스레드 종료시킨다
            Thread.Sleep(100);
            Console.WriteLine("Step 5: " + t.ThreadState);
        }
    }
}

Step 1: Unstarted
Step 2: Running
Step 3: Suspended
Step 4: Running
Step 5: Aborted

 

예제 6.21 (완전수 join메소드 이용해서)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ThreadJoinApp
{
    class ThreadJoin
    {
        public int start;
        public int perfectNumber;
        public void ThreadBody()
        {
            int sum;
            for (int i = start; ; i++)
            {
                sum = 0;
                for (int j = 1; j <= i / 2; j++)
                    if (i % j == 0) sum += j;
                if (i == sum)
                {
                    perfectNumber = i;
                    break;
                }
            }
        }
    }
    class Program
    {
        public static void Main()
        {
            ThreadJoin obj = new ThreadJoin();
            ThreadStart ts = new ThreadStart(obj.ThreadBody);
            Thread t = new Thread(ts);
            Console.Write("Enter a number : ");
            obj.start = int.Parse(Console.ReadLine());
            t.Start();
            t.Join();   // join 생략하면 출력값 0
            Console.WriteLine("The perfect number over {0} is {1}.", obj.start, obj.perfectNumber);
        }
    }
}

Enter a number : 100   (input)
The perfect number over 100 is 496.    (output)

 

예제 6.22 (현재스레드이 우선순위, 가장높은우선순위 출력)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ThreadPriorityApp
{
    class Program
    {
        static void ThreadBody()
        {
            Thread.Sleep(1000);
        }
        public static void Main()
        {
            Thread t = new Thread(new ThreadStart(ThreadBody));
            t.Start();
            Console.WriteLine("Current Priority : " + t.Priority);
            ++t.Priority;
            Console.WriteLine("Higher Priority : " + t.Priority);
        }
    }
}

Current Priority : Normal
Higher Priority : AboveNormal

 

예제 6.23
using System;
using System.Threading;
class SchedulerApp
{
    static int interval;
    static void ThreadBody()
    {
        Thread myself = Thread.CurrentThread;
        Console.WriteLine("Starting Thread : " + myself.Name);
        for (int i = 1; i <= 3 * interval; i++)
        {
            if (i % interval == 0)
                Console.WriteLine(myself.Name + " : " + i);
        }
        Console.WriteLine("Ending Thread : " + myself.Name);
    }
}
public static void Main()
{
    Console.Write("Interval value : ");
    interval = int.Parse(Console.ReadLine());
    Thread.CurrentThread.Name = "Main Thread";
    Thread worker = new Thread(new ThreadStart(ThreadBody));
    worker.Name = "Worker Thread";
    worker.Start();
    ThreadBody();
}

Interval value : 1000000    (input)

(output) :
Starting Thread : Main Thread
Starting Thread : Worker Thread
Main Thread : 1000000
Worker Thread : 1000000
Main Thread : 2000000
Worker Thread : 2000000
Main Thread : 3000000
Ending Thread : Main Thread
Worker Thread : 3000000
Ending Thread : Worker Thread

 

예제 6.24 (lock문 : 동기화문제해결위해)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace LockStApp
{
    class ThreadProperty
    {
        public void ThreadBody()
        {
            Thread myself = Thread.CurrentThread;
            lock (this)
            {
                for (int i = 1; i <= 3; i++)
                {
                    Console.WriteLine("{0} is activated => {1}", myself.Name, i);
                    Thread.Sleep(1000);
                }
            }
        }
    }
    class Program
    {
        public static void Main()
        {
            ThreadProperty obj = new ThreadProperty();
            ThreadStart ts = new ThreadStart(obj.ThreadBody);
            Thread t1 = new Thread(ts);
            Thread t2 = new Thread(ts);
            t1.Name = "Apple"; t2.Name = "Orange";
            t1.Start(); t2.Start();
        }
    }
}

Apple is activated => 1
Apple is activated => 2
Apple is activated => 3
Orange is activated => 1
Orange is activated => 2
Orange is activated => 3

 

예제6.25 

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

namespace MonitorApp
{
    class ThreadProperty
    {
        public void ThreadBody()
        {
            Thread myself = Thread.CurrentThread;
            Monitor.Enter(this);
            for (int i = 1; i <= 3; i++)
            {
                Console.WriteLine("{0} is activated => {1}", myself.Name, i);
                Thread.Sleep(1000);  // 1초
            }
            Monitor.Exit(this);
        }
    }
    class Program
    {
        public static void Main()
        {
            ThreadProperty obj = new ThreadProperty();
            ThreadStart ts = new ThreadStart(obj.ThreadBody);
            Thread t1 = new Thread(ts);
            Thread t2 = new Thread(ts);
            t1.Name = "Apple"; t2.Name = "Orange";
            t1.Start(); t2.Start();
        }
    }
}

Apple is activated => 1
Apple is activated => 2
Apple is activated => 3
Orange is activated => 1
Orange is activated => 2
Orange is activated => 3

 

 

[과제]연습문제6.11 (제네릭클래스로 swap프로그램)
using System;

class Swap_Generic<T>
{
    public T x,y;
    public void swap()
    {
        T temp;
        temp = x; x = y;y = temp;

    }
}
public class ExerciseC6_11
{
    public static void Main(String[] args)
    {
        Swap_Generic<int> i = new Swap_Generic<int>();
        i.x = 15; i.y = 51;
        Console.WriteLine("x: " + i.x + " y: " + i.y);
        i.swap();
        Console.WriteLine("x : " + i.x + " y : " + i.y);

        Swap_Generic<double> d =new Swap_Generic<double>();
        d.x = 15.1; d.y = 80.6;
        Console.WriteLine("x: " + d.x + "y: " + d.y);
        d.swap();
        Console.WriteLine("x: " + d.x + "y: "+d.y);
    }
}

x: 15 y: 51
x : 51 y : 15
x: 15.1y: 80.6
x: 80.6y: 15.1

 

[과제] 연습문제6.14 (2) (lock문을 사용하여 은행 예금 문제를 해결한 클래스)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace LockStApp
{
    class ThreadProperty
    {
        public void ThreadBody()
        {
            Thread myself = Thread.CurrentThread;
            lock (this)
            {
                for (int i = 1; i <= 3; i++)
                {
                    Console.WriteLine("{0} is activated => {1}", myself.Name, i);
                    Thread.Sleep(1000);
                }
            }
        }
    }
    class Program
    {
        public static void Main()
        {
            ThreadProperty obj = new ThreadProperty();
            ThreadStart ts = new ThreadStart(obj.ThreadBody);
            Thread t1 = new Thread(ts);
            Thread t2 = new Thread(ts);
            t1.Name = "Apple"; t2.Name = "Orange";
            t1.Start(); t2.Start();
        }
    }
}

3 : 9600
1 : 9800
2 : 10100
4 : 9600