Code C#: Cơ chế ủy quyền (Delegate) trong C# (P.1)

Người đăng: share-nhungdieuhay on Thứ Năm, 4 tháng 4, 2013



Ví dụ 1: Khai báo cơ chế ủy quyền (delegate) trong C# gọi các phương thức thực thi
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Delegates{
    public delegate int MyDelegate(int x, int y);
    
    public class Vidu1{
        public static int Cong(int x, int y){
            return x + y;
        }
        public static int Nhan(int x, int y) {
            return x * y;
        }
    }
    
    class Program{
        static void Main(string[] args){
            MyDelegate del1 = new MyDelegate(Vidu1.Cong);
            int KetquaCong = del1(5, 5);
            Console.WriteLine("5 + 5 = {0}", KetquaCong);
            MyDelegate del2 = new MyDelegate(Vidu1.Nhan);
            int KetquaNhan = del2(5, 5);
            Console.WriteLine("5 x 5 = {0}", KetquaNhan);
            Console.ReadLine();
        }
    }
}


{ 0 nhận xét... read them below or add one }

Đăng nhận xét