首页 > 其他 > 详细

c#编程基础

时间:2014-03-04 09:36:32      阅读:395      评论:0      收藏:0      [点我收藏+]

1、什么是委托?

委托就是可以把一个方法作为一个参数带入另一个方法中去。但是委托不是一个方法,而是一种类型。

2、如何使用委托?

在使用委托的时候我们可以像使用一个类一样去实例化它,而与类不同的是。类实例化完成后就是一个对象,而委托实例化后还是一个委托。

 

3、使用委托的步骤:

例:先声明一个委托

   1:   /// <summary>
   2:   /// 此处声明了一个返回值为空,参数为字符串的委托
   3:   /// </summary>
   4:   /// <param name="str"></param>
   5:  public delegate void MyDelegate(string str);
    

定义一个和委托一样返回值类型和参数类型的方法:

   1:   public class c
   2:          {
   3:              public static void M1(string str)
   4:              {
   5:                  Console.WriteLine("这是第{0}个委托",str);
   6:              }
   7:              public static void M2(string str)
   8:              {
   9:   
  10:                  Console.WriteLine("这是第{0}个委托",str);
  11:              }
  12:          }

调用委托实现

   1:   static void Main(string[] args)
   2:          {
   3:              MyDelegate myDelegate1 = new MyDelegate(c.M1);
   4:              myDelegate1("1");
   5:              MyDelegate myDelegate2 = new MyDelegate(c.M2);
   6:              myDelegate2("2");
   7:              Console.Read();
   8:          }

4、完整代码实现

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:   
   6:  namespace 委托
   7:  {
   8:     
   9:      class Program
  10:      {
  11:          static void Main(string[] args)
  12:          {
  13:              MyDelegate myDelegate1 = new MyDelegate(c.M1);
  14:              myDelegate1("1");
  15:              MyDelegate myDelegate2 = new MyDelegate(c.M2);
  16:              myDelegate2("2");
  17:              Console.Read();
  18:          }
  19:          /// <summary>
  20:          /// 此处声明了一个返回值为空,参数为字符串的委托
  21:          /// </summary>
  22:          /// <param name="str"></param>
  23:          public delegate void MyDelegate(string str);
  24:          /// <summary>
  25:          /// 
  26:          /// </summary>
  27:          public class c
  28:          {
  29:              public static void M1(string str)
  30:              {
  31:                  Console.WriteLine("这是第{0}个委托",str);
  32:              }
  33:              public static void M2(string str)
  34:              {
  35:   
  36:                  Console.WriteLine("这是第{0}个委托",str);
  37:              }
  38:          }
  39:          
  40:      }
  41:  }

c#编程基础,布布扣,bubuko.com

c#编程基础

原文:http://www.cnblogs.com/ilooking/p/3578726.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!