2012. 12. 15. 14:52ㆍ2010년/C#.NET
Delegate를 즉 대리자라는 사전적 의미가 있다.
그러면 Delegate를 왜 사용할까? 라는 생각에 기존에 C나 C++같은경우는 함수,메서드를 단지 포인터를 통해서 찾아가고 가져오고 했다. 하지만 C#에서는 포인터개념이 없이 함수와 메서드를 사용할수 있는 Delegate가 있다. 딱 코드처보고 놀란건.. 와 쩐다는 느낌의 개념이었고 함수포인터보다 더 쉽게 사용할수있다는것이다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Delegate_01
{
delegate void deleMath(int Value); //delemath선언
class Program
{
static void Main(string[] args)
{
MathClass mathcalss = new MathClass(); //Math 클래스의 할댱
deleMath math = new deleMath(mathcalss.Plus); //delemath할댱과 동시에 Math클래스 메서드 plus를 연결
math += new deleMath(mathcalss.Minus); //Math클래스 메서스 minus를 추가
math += new deleMath(mathcalss.Multiply); //Math클래스 메서스 mutiply 를 추가
mathcalss.Number = 10;
math(10);
Console.WriteLine("Result :{0}", mathcalss.Number);
//값이 plus,minus,mutiply 메서드를 한번씩 사용하고 나옴 값이 100
math -= new deleMath(mathcalss.Minus);
mathcalss.Number = 10;
math(10);
Console.WriteLine("Result :{0}", mathcalss.Number);
//위에 값에서 minus 메서드를 뺏기때문에 200
math -= new deleMath(mathcalss.Multiply);
mathcalss.Number = 10;
math(10);
Console.WriteLine("Result :{0}", mathcalss.Number);
//메서스 mutiply도 뺏기때문에 20
}
}
class MathClass
{
public int Number;
public void Plus(int value)
{
Number += value;
}
public void Minus(int value)
{
Number -= value;
}
public void Multiply(int value)
{
Number *= value;
}
}
}
출처 - HOONS-
'2010년 > C#.NET' 카테고리의 다른 글
C# 도서관리 프로그램 (0) | 2012.12.15 |
---|---|
C# Oracle 연결및 확인 (0) | 2012.12.15 |