0322 delegate 연습
2021. 3. 23. 00:38ㆍC#/과제
delegate int Delelegate(int a, int b);
class Program
{
static int Plus(int a, int b)
{
return a + b;
}
static void Main(string[] args)
{
Delelegate pd1 = Plus;
Delelegate pd2 = delegate (int a, int b)
{
return a / b;
};
Console.WriteLine(pd1(5, 10));
Console.WriteLine(pd2(10, 5));
}
}
public class App
{
public App()
{
//1. 기존 메서드 지정
Action<string> action1 = Print;
action1("1.기본 메서드 지정 방식");
//2. 무명 메서드 지정
Action<string, string> action2 = delegate (string msg, string error)
{
Console.WriteLine(msg, error);
};
action2("2. 무명 메서드 지정", "Inform");
}
public void Print(string msg)
{
Console.WriteLine(msg);
}
}
public class App
{
delegate int DelCalculate(int x, int y);
public App()
{
DelCalculate delCalculate = new DelCalculate(Plus);
int result = delCalculate(20, 10);
Console.WriteLine("result: " + result);
DelCalculate delCalculate2 = new DelCalculate(Substract);
int result1 = delCalculate2(20, 10);
Console.WriteLine("result: " + result1);
}
public int Plus(int x, int y)
{
return x + y;
}
public int Substract(int x, int y)
{
return x - y;
}
}
public class App
{
public delegate void DelCalculate(int x, int y);
public App()
{
DelCalculate plus = Plus;
DelCalculate substract = Substract;
DelCalculate multiple = Multiple;
DelCalculate divide = Divide;
Callback(20, 10, plus);
Callback(20, 10, substract);
Callback(20, 10, multiple);
Callback(20, 10, divide);
}
public void Callback(int x, int y, DelCalculate dele)
{
dele(x, y);
}
public void Plus(int x, int y)
{
Console.WriteLine(x + y);
}
public void Substract(int x, int y)
{
Console.WriteLine(x - y);
}
public void Multiple(int x, int y)
{
Console.WriteLine(x * y);
}
public void Divide(int x, int y)
{
Console.WriteLine(x / y);
}
}
public delegate void OnCharaMove();
public class Chara
{
public OnCharaMove OnCharaMove;
public Chara()
{ }
public void Move(string name)
{
this.OnCharaMove();
Console.WriteLine("{0} 캐릭터가 이동합니다.",name);
}
}
public class App
{
public App()
{
Chara chara = new Chara();
chara.OnCharaMove = this.OnCharaMove;
chara.Move("홍길동");
}
public void OnCharaMove()
{
Console.WriteLine("유저가 마우스를 클릭합니다.");
}
}
'C# > 과제' 카테고리의 다른 글
0329 스레드 복습 (0) | 2021.03.29 |
---|---|
0317 interface+abstract+stack+queue (0) | 2021.03.17 |
0316 컬랙션 과제 (0) | 2021.03.17 |
0314 클래스와 메서드 (0) | 2021.03.15 |
0311 Class+맴버 변수+메서드 호출 연습 (0) | 2021.03.11 |