SQL 面向对象(委托)

委托:
也称为代理,事件也是一种委托;
定义在类的最外面

1、定义委托
关键字:delegate
函数签名:签名和函数保持一致
定义委托的时候要根据函数来定义
public delegate int First(int a,int b);
指向的方法的返回类型,需要参数必须一致!

2、定义委托变量,指向方法

委托不能被实例化,因为不是类;

First f = new JiaFa; //新建委托变量,指向方法,注意!!方法不需要小括号!!

第二次可以使用+=

public int JiaFa(int a,int b)
{
return a+b;
}

调用:
f(5,3);

可以理解为函数的指针,委托指向哪个函数,则这个委托就代表哪个函数
可以让函数当做参数一样进行传递

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ConsoleApplication1
{
//单列模式
//控制一个类只能实例化一个对象 //class Test
//{
// public string name;
//} //数据访问类
class DBDA
{
public string host;
public string database; //静态成员,用来存储该类的对象
public static DBDA db = null; //让该类不能被实例化
private DBDA()
{
} //提供一个造对象的方法,控制只能造一个对象
public static DBDA DuiXiang()
{
if (db == null)
{
db = new DBDA();
} return db;
}
} //定义委托
public delegate void SuiBian(string s); class Program
{
static void Main(string[] args)
{
// Test t1 = new Test();
//Test t2 = new Test(); //DBDA db = DBDA.DuiXiang();
//db.host = "localhost";
//DBDA db1 = DBDA.DuiXiang(); //委托
//把方法参数化
SuiBian s = China; s += America; //+=是绑定方法 -=去掉一个方法 //事件
//事件就是一种特殊的委托 //调用语音方法
Speak(s); Console.WriteLine();
Console.ReadLine(); //面向对象三大特性
//设计模式
} //语音功能的方法
static void Speak(SuiBian yu)
{
yu("张三"); //if (n == 0)
//{
// America();
//}
//else if (n == 1)
//{
// China();
//}
//else if (n == 2)
//{
// HanYu();
//} } //语音包
public static void America(string s)
{
Console.WriteLine(s+"hello");
}
public static void China(string s)
{
Console.WriteLine(s+"你好");
}
public static void HanYu(string s)
{
Console.WriteLine(s+"bjdkaj");
} }
}
上一篇:Linux进程间通信——使用流套接字


下一篇:Python中的“命名元组”是什么? - What are “named tuples” in Python?