using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LearnDelegate
{
//Delegate nhận một tham số là kiểu string và trả về kiểu void
public delegate void MsgBox(string s);
//Delegate không nhận tham số và trả về kiểu void
public delegate void Chao();
//Delegate nhận hai tham số kiển int và trả về kiểu int
public delegate int Plus(int a, int b);
//Lớp Greeting
class Greeting
{
public void TiengViet(string ten)
{
Console.WriteLine("Xin chao " + ten);
}
public void Chao()
{
Console.WriteLine("Xin chao ");
}
public void English(string name)
{
Console.WriteLine("Hello " + name);
}
}
//Lớp Calc
class Calc
{
public int add(int x1, int x2)
{
return x1 + x2;
}
}
//Lớp LearnDelegate có hàm main
public class LearnDelegate
{
public static void Main()
{
//Khai bao một đối tượng greeting
Greeting gr = new Greeting();
//Khai báo một đối tược Calc
Calc ca = new Calc();
MsgBox deg;//Khai báo một delegate MsgBox
Chao chao;//Khai báo một delegate Chao
Plus plus;//Khai báo một đối tượng Plus
//Ủy nhiệm phương thức Tiengviet cho delegate MsgBox
deg = new MsgBox(gr.TiengViet);
//Triệu gọi delegate
deg.Invoke("Hung");
/*Ủy nhiệm phương thức English của lớp Greeting
cho delegate MsgBox*/
deg = new MsgBox(gr.English);
//Triệu gọi delegate
deg.Invoke("Hung");
/*ủy nhiệm phương thức chao của lớp Greeting
cho delegate Chao*/
chao = new Chao(gr.Chao);
//Triệu gọi delegate
chao.Invoke();
/*Ủy nhiệm phương thức add của lớp Calc
cho Delegate Plus*/
plus = new Plus(ca.add);
//In kết quả phép cộng ra màn hình
Console.WriteLine(plus.Invoke(3, 6));
//Dừng màn hình
Console.Read();
}
}
}
5/09/2010
Delegate trong C#
Labels:
C#
Subscribe to:
Post Comments (Atom)
The 0/1 Knapsack Problem - Dynamic Programming
References: https://www.youtube.com/watch?v=EH6h7WA7sDw Class Item class Item { private $_weight; private $_value; public functi...
-
Set Alternating Row Styles for the Windows Forms DataGridView Control Rất đơn giản chỉ có hai dòng, một dòng cho màu mặc định, và một dòng...
-
Trước tiên tạo một class ColorTable.java import java.awt.Color; import javax.swing.JTable; import javax.swing.table.*; public class Col...
-
References: https://www.youtube.com/watch?v=EH6h7WA7sDw Class Item class Item { private $_weight; private $_value; public functi...
No comments:
Post a Comment