委托的是含义,如果你学过C那么你可以把委托理解为C里面的函数指针,如果你没学过其他的语言,你可以理解为自定义类型.
声明委托要使用关键字delegate,代码如下
delegate void ShowName()
学过C的:上面相当于声明了一个类型为ShowName的指针,由于C里面的指针指向的是内存中的一个实际地址,具有一定的不安全型,C#在这里做了相应的改进,必须指向具有相同签名的函数.
直接开始C#学习读者:上面就相当于定义了一个Showname类型的自定义类型,跟系统定义的int,double类型差不多.
类型定义完了接着就是声明这种类型的变量了,和声明int,double等类型的变量差不多.
ShowName sn1;
ShowName sn2;
接下来就是给变量赋值,这里的赋值就把和定义时相同签名的函数(或者叫方法)传给上面定义的变量.赋值一共有三种语法格式.
下面我给出一个完整的代码
using System;
using System.Collections;
![](/Images/OutliningIndicators/None.gif)
//定义委托类型
delegate void ShowInfo();
class Info
{
public void MyName()
{
Console.Write("Name:林.Net ");
}
public void MyAge()
{
Console.Write("Age:28");
}
}
![](/Images/OutliningIndicators/None.gif)
public class Client
{
public static void Main( string[] args )
{
Info info = new Info();
ShowInfo si ;//声明委托变量
si = info.MyName;
si += info.MyAge;
si();
}
}
声明委托要使用关键字delegate,代码如下
![](/Images/OutliningIndicators/None.gif)
直接开始C#学习读者:上面就相当于定义了一个Showname类型的自定义类型,跟系统定义的int,double类型差不多.
类型定义完了接着就是声明这种类型的变量了,和声明int,double等类型的变量差不多.
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
接下来就是给变量赋值,这里的赋值就把和定义时相同签名的函数(或者叫方法)传给上面定义的变量.赋值一共有三种语法格式.
//第一种
sn1 = new ShowName(MyName);
//第二种
sn1 = MyName;
//第三种
sn1 = delegate(){//}
sn1 = new ShowName(MyName);
//第二种
sn1 = MyName;
//第三种
sn1 = delegate(){//}
下面我给出一个完整的代码
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)