티스토리 뷰

Today I learned/C#

delegate(델리게이트)

하늘_다람쥐 2017. 10. 24. 23:54

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace delegateCalculator { class Program { static void Main(string[] args) { Calculator cal = new Calculator(); Console.WriteLine("Add Result : " + cal.a(1, 2, 3, 4, 5));

//무제한 인수를 통해 2개 이상의 인자를 모두 받을 수 있음 Console.WriteLine("Sub Result : " + cal.s(10, 1, 2, 3, 4));

//10 - 1 - 2 - 3 - 4 = 0 Console.WriteLine("Mul Result : " + cal.m(1, 2, 3, 4, 5));

//5!(factorial) Console.WriteLine("Div Result : " + cal.d(5, 2));

// 5/2 = 2 } } class Calculator { static int add(params/*인수 개수 무제한*/ int[] data) { int res = 0; foreach(int val in data)

//무제한으로 받은 인수의 배열 요소를 모두 더함 { res += val; } return res; } static int sub(int first,params int[] data) { int res = first; foreach (int val in data) { res -= val; } return res; } static int mul(params int[] data) { int res = 1; foreach(int val in data) { res *= val; } return res; } static int div(int a, int b) { return a / b; } public delegate int addDelegate(params int[] data);

//delegate 메소드 정의 public delegate int subDelegate(int first, params int[] data); public delegate int mulDelegate(params int[] data); public delegate int divDelegate(int a, int b); public addDelegate a = new addDelegate(add);

//delegate 변수를 만들고 메소드를 넣음 public subDelegate s = new subDelegate(sub); public mulDelegate m = new mulDelegate(mul); public divDelegate d = new divDelegate(div); } }


배우려고 대충 쓴 코드.  C, C++의 함수포인터 개념이다. 메소드를 델리게이트를 통해 대신 호출한다. 여기서는 계산기의 계산 기능들을 a,s,m,d라는 델리게이트 변수를 통해 대신 수행함

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함