委托和类一样,是一种用户自定义的类型。但类表示的是数据和方法的集合,而委托则持有一个或多个方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 委托
{
//定义一个返回值为int类型且参数为空的委托
delegate int My_delegate();
class Program
{
static void Main(string[] args)
{ //声明变量
int y = 0;
//创建一个空委托
My_delegate del;
//创建一个类的实例对象
My_class mc = new My_class();
//初始化该委托
del = mc.Add;
//给委托添加另一个方法
del += mc.Subtraction;
//判断委托是否为空
if (del != null)
{
//调用委托
int z = del();
Console.WriteLine(z.ToString());
}
else
{
Console.WriteLine("委托为空!");
}
Console.WriteLine("-----结束-----");
Console.Read();
}
}
public class My_class
{
int x = 0;
//加法
public int Add()
{
x += 50;
return x;
}
//减法
public int Subtraction()
{
x -= 20;
return x;
}
}
}