2012년 4월 24일 화요일

델리게이트




001: using System;
002: //델리게이트 선언
003: delegate void dele1();
004: delegate int dele2(int a,int b);
005: class MainClass
006: {
007:    static void Main(string[] args)
008:    {
009:           //Math클래스 선언및 인스턴스화
010:           MathClass MathClass=new MathClass();
011:           //델리게이트 선언및 인스턴스화
012:           dele1 Sum1=new dele1(MathClass.Intro);
013:           dele2 Sum2=new dele2(MathClass.Sum);
014:           //델리게이트에 위임된 메서드 실행
015:           Sum1();
016:           Console.WriteLine("Result : {0}",Sum2(-10,90));
017:    }
018: }
019: class MathClass
020: {
021:    public void Intro()
022:    {
023:           Console.WriteLine("계산을 시작합니다.");
024:    }
025:    public int Sum(int a, int b)
026:    {
027:           return a+b;
028:    }
029: }




using System;
002: delegate void deleMath(int Value); //델리게이트 선언
003: class MainClass
004: {
005:    static void Main(string[] args)
006:    {
007:           //Math클래스 선언및 인스턴스화
008:           MathClass MathClass=new MathClass();
009:        
010:           //델리게이트 선언및 인스턴스화(덧셈)
011:           deleMath Math=new deleMath(MathClass.Plus);
012:
013:           //위임연산(뺄셈,곱셈추가)
014:           Math+=new deleMath(MathClass.Minus);
015:           Math+=new deleMath(MathClass.Multiply);
016:           //결과1
017:           MathClass.Number=10;
018:           Math(10);
019:           Console.WriteLine("Result:{0}",MathClass.Number);
020:
021:           //위임연산(뺄셈제거)
022:           Math-=new deleMath(MathClass.Minus);
023:           //결과2
024:           MathClass.Number=10;
025:           Math(10);
026:           Console.WriteLine("Result:{0}",MathClass.Number);
027:
028:           //위임연산(곱셈제거)
029:           Math-=new deleMath(MathClass.Multiply);
030:           //결과3
031:           MathClass.Number=10;
032:           Math(10);
033:           Console.WriteLine("Result:{0}",MathClass.Number);
034:
035:    }
036: }
037: class MathClass
038: {
039:    public int Number;
040:    public void Plus(int Value)//더하기
041:    {
042:           Number+=Value;
043:    }
044:    public void Minus(int Value)//빼기
045:    {
046:           Number-=Value;
047:    }
048:    public void Multiply(int Value)//곱하기
049:    {
050:           Number*=Value;
051:    }
052: }

출처
http://hoons.kr/Lecture/LectureMain.aspx?BoardIdx=61&kind=4&view=0

댓글 없음 :

댓글 쓰기