这是我早期写的,不知道对你有没帮助,拿给你看看,委托只有在事件里才能深刻弄明白
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 定义委托
{
class Program
{
//委托是不能定义返回值的;
delegate void delegateone();//定义了一个不包含参数的委托类型;
delegate void delegatetwo(params int[] values);//定义了一个包含参数的委托类型;
static void Methoddelegateone()
{
Console.WriteLine("Hello.World" + " " + "!");
}
static void Methoddelegatetwo(params int[] values)
{
for (int i = 0; i < values.Length - 1; i++)
{
for (int j = 0; j < values.Length - i - 1; j++)
{
int temp;
if (values[j] <= values[j + 1])
{
temp = values[j];
values[j] = values[j + 1];
values[j + 1] = temp;
}
}
}
foreach (int i in values)
{
Console.Write(i + " ");
}
Console.Write("\n");
}
static void MethoddelegatetwoAvg(params int[] values)
{
int sum = 0;
for (int i = 0; i < values.Length;i++ )
{
sum += values[i];
}
Console.WriteLine("总成绩为{0}{1},平均成绩为{0}{2}"," ",sum,(double)sum/values.Length);
}
static void Main(string[] args)
{
ShowUi();
int number=0;
Console.WriteLine("请输入你们班级人数?");
try
{
number = Convert.ToInt32(Console.ReadLine());
if (number<0)
{
MessageBox.Show("人数不能为负数");
return;
}
else
{
Console.WriteLine("------------------------------------------------");
}
}
catch
{
MessageBox.Show("人数只能是数字");
return;
}
int [] score =new int[number];//这里的number必须先定义,赋值再使用;
for (int i = 0; i < score.Length;i++ )
{
Console.WriteLine("请输入第{0}个学生的成绩?",i+1);
try
{
score[i] = Convert.ToInt32(Console.ReadLine());
if (score[i]<0||score[i]>100)
{
MessageBox.Show("学生成绩不能为负数,也不能大于100");
return;
}
else
{
delegateone onedelegate = new delegateone(Methoddelegateone);
delegatetwo twodelegate=null;
twodelegate+= new delegatetwo(Methoddelegatetwo);
twodelegate += new delegatetwo(MethoddelegatetwoAvg);
1,委托(Delegate)类是一种数据结构,通过它可引用静态方法或引用类实例及该类的实例方法;
2,Delegate在搭载多个方法时,可以通过+=增加搭载的函数,也可以通过-=来去掉Delegate中的某个函数
3,class Program
{
static void OtherClassMethod()
{
Console.WriteLine("Delegate an other class's method");
}
static void Main(string[] args)
{
var test = new TestDelegate();
//delegateMethod搭载了3个函数
test.delegateMethod = new TestDelegate.DelegateMethod(test.NonStaticMethod);
test.delegateMethod += new TestDelegate.DelegateMethod(TestDelegate.StaticMethod);
test.delegateMethod += Program.OtherClassMethod;
test.RunDelegateMethods();
}
}
class TestDelegate
{
public delegate void DelegateMethod(); //声明了一个Delegate Type,DelegateMethod是类型
public DelegateMethod delegateMethod; //声明了一个Delegate对象,delegateMethod是对象
public static void StaticMethod() //调用静态方法
{
Console.WriteLine("Delegate a static method");
}
public void NonStaticMethod() //调用非静态方法
{
Console.WriteLine("Delegate a non-static method");
}