感觉这些是对委托的经典概况,就是函数指针,但是比函数指针更加具有类型的安全性,规定 了方法的所有细节。
委托使用通用需要先申明定义,然后初始化。
下面是使用委托做参数,比较2个类的大小(自定义的函数比较,作为参数指针穿进去)
比较2个函数的重载。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestWhile
{
class BubbleSorter
{
//委托
public delegate bool Comparsion(object x, object y);
// 排序 comparsion 传进来的实例化委托(函数指针)
public static void Sort(object[] sortArray, Comparsion comparsion) {
for (int i = 0; i < sortArray.Length; i++)
{
for (int j = i + 1; j < sortArray.Length; j++) {
if (comparsion(sortArray[j], sortArray[i])) { // 委托使用
object tem = sortArray[i];
sortArray[i] = sortArray[j];
sortArray[j] = tem;
}
}
}
}
// 函数重载
public static void Sort(int[] sortArray) {
for(int i = 0; i < sortArray.Length; i++)
{
for (int j = i + 1; j < sortArray.Length; j++) {
if (sortArray[i] > sortArray[j])
{
int temp = sortArray[i];
sortArray[i] = sortArray[j];
sortArray[j] = temp;
}
}
}
}
}
}
在需要排序的类中加入方法排序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestWhile
{
class Emploee
{
int salary;
string name;
public Emploee(string name, int salary) {
this.name = name;
this.salary = salary;
}
// 重写tostring方法
public override string ToString()
{
return string.Format("{0},{1:c}",name,salary);
}
public static bool ComplaySalary(object x, object y) {
Emploee e1 = (Emploee)x;
Emploee e2 = (Emploee)y;
return (e1.salary < e2.salary);
}
static void Main(string[] args)
{
Emploee[] emploee = { new Emploee("xiaolin",45),
new Emploee("xiaofen",36),
new Emploee("xiaozhan",5),
new Emploee("xiaoqian",50),
new Emploee("xiaosun",495),
new Emploee("xiaozhou",85)};
BubbleSorter.Sort(emploee,Emploee.ComplaySalary);//传函数指针(委托)
/*
补充:一个面试题,unity项目
GameObject[] go= new GameObject[10]; 错误:本语句仅仅申明数组,
for(int i=0;i<go.Length;i++)
go.AddComponet<script>(); 空指针,并没有初始化
*/
foreach (var memploee in emploee) {
Console.WriteLine(memploee.ToString());
}
Console.WriteLine("-----------------------");
int[] a = {3,5,23,1,55,3,57 };
BubbleSorter.Sort(a);
foreach(int aa in a)
{
Console.WriteLine(aa);
}
Console.ReadKey();
}
}
}
多播委托 类似于存放函数的指针的集合,调用的时候,依次调用该集合里面的每个方法
委托定义
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestWhile
{
class mydelegate
{
public delegate void Mydelegate(); // s申明一个委托(申明一个委托类)
public Mydelegate mytestDelegate; // d创建一个委托对象
public void A()
{
Console.WriteLine("a");
}
public void B()
{
Console.WriteLine("b");
}
}
}
mydelegate myD = new mydelegate();
myD.mytestDelegate = myD.A; //委托赋值. 将委托赋值给A函数
myD.mytestDelegate();
Console.WriteLine("=========================");
myD.mytestDelegate += myD.B;
myD.mytestDelegate();
Console.WriteLine("=========================");
myD.mytestDelegate -= myD.A;
myD.mytestDelegate();
Console.ReadKey();
两个编程错误,仅供参考,静态函数调用非静态方法 2静态public函数,传入private指针