C#学习之------委托

时间:2023-03-09 05:52:27
C#学习之------委托

1、向窗体中添加控件的最少步骤:                 窗体的句柄为this

private System.Windows.Forms.Button button1;                //声明button类变量button1

this.button1 = new System.Windows.Forms.Button();       //创建button对象,其(name属性)句柄为button1-----实例化

this.Controls.Add(this.button1);                                      //通过句柄button1,将button1控件添加到窗体中

c#委托声明实例化与调用

转载地址:http://blog.csdn.net/han_yankun2009/article/details/25919565

系统访问数据或调用方法有两种操作方式:一种是通过名称访问或调用,另一种是通过所在的内存地址来访问调用。为了系统的安全与稳定,NET Framework的CLR库不允许程序通过指针来直接操作内存中数据或方法,而是通过托管机制来访问内存中数据或调用内存中的方法。委托就是C#提供的一种以托管机制调用方法的特殊数据类型,其作用于房屋租凭中介机构类似。
 
下面我们主要围绕以下三点
 
    //1.定义委托  
    //2.委托的实例化 
    //3.委托的调用,实际上是将委托指向已经实现的某个方法 
 
    //注意:调用的方法必须返回类型和定义的委托返回类型一致 
 
 
 委托是一个类,它定义了方法的类型,使得可以将方法当做参数进行传递。
 
一:委托的定义
 
在C#中使用关键字delegate声明委托。声明委托的一般形式是:
 
//委托的定义  
    // [访问修饰符]  delegate  数据类型  委托名(参数列表....) 
 
在使用委托前是一定先要定义的
  1. 例如:Delegate void d(int x)

2、public delegate void dlgleixing(string str);     //声明了一个参数为string str无返回值的delegate类型
 
二:实例化( 与方法绑定) 


为了与命名方法一起使用,委托必须用具有可接受签名的方法进行实例化。
 
实例化的方法可用下列方法各项之一
  • “委托创建表达式”中引用的静态方法,或者
  • “委托创建表达式”中引用的目标对象(此对象不能为 null)和实例方法
  •  另一个委托

例如:

  1. Delegate void d(int x)
  2. delegate void D(int x);
  3. class C
  4. {
  5. public static void M1(int i) {...}
  6. public void M2(int i) {...}
  7. }
  8. class Test
  9. {
  10. static void Main() {
  11. D cd1 = new D(C.M1);      // static method
  12. Test t = new C();
  13. D cd2 = new D(t.M2);      // instance method
  14. D cd3 = new D(cd2);      // another delegate
  15. }
  16. }

三.委托调用


 
创建委托对象后,通常将委托对象传递给将调用该委托的其他代码。通过委托对象的名称(后面跟着要传递给委托的参数,括在括号内)调用委托对象。下面是委托调用的示例:
  1. public delegate int MathOp(int i,int j);//定义委托
  2. class DelegateTest
  3. {
  4. public static int  add(int i, int j) {//方法
  5. return i + j;
  6. }
  7. public static int Mutiply(int num1, int num2) {//方法
  8. return num1 * num2;
  9. }
  10. static void Main(string[] args)
  11. {
  12. MathOp mo = new MathOp(add);//委托的实例化,指向add方法
  13. MathOp maOp = new MathOp(Mutiply);//委托的实例化,指向Mutiply方法
  14. Console.WriteLine(mo(10, 20));//委托的调用
  15. Console.WriteLine(maOp(4, 5));//委托的调用
  16. Console.ReadLine();
  17. }
  18. }
  19. }

认识:

以前对委托的认识只是知道委托是方法的调用。通过这次的项目实例了解到委托也是需要定义,实例化与调用的。还是先前学艺不精占呀。委托的使用通常与匿名函数或lambda表达式匹配使用,下篇介绍匿名函数