ASP.NET温故而知新学习系列之ASP.NET多线程编程—.NET下的多线程编程委托使用的实例(五)

来源:互联网 发布:淘宝助理 顺丰模板 编辑:程序博客网 时间:2024/06/05 10:01

阅读目录

  一:委托与线程

  二:委托使用的实例

  三:运行效果

  一:委托与线程

  .委托基础
  -委托使用的目的:把函数作为参数传递
  -类似于C++中的函数指针,和函数指针是有区别的:函数指针只能引用静态方法,而委托可以引用静态方法,也可以引用实例方法,当委托引用实例方法时,委托不仅存储对方法入口点的引用,还存储对调用该方法的实例引用
  -是事件处理的基础
  -委托声明:delegate int MyDelegate (int i); int表示函数返回类型,MyDelegate表示委托名称,i表示函数参数

  二:委托使用的实例

  1:声明委托

  delegate int MyDelegate(int i);

  2:定义一个静态方法,返回两数的乘积

  public static int DelegateMethod(int i)

  {
     return i * i;

  }

  3:声明一个委托变量mydelegate,且绑定到静态方法DelegateMethod

  MyDelegate mydelegate = new MyDelegate(DelegateMethod);

  实例

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;

  namespace _3_DelegateUse
  {
      class Program
      {
          //step1声明委托
          public delegate int MyDelegate(int i);
          static void Main(string[] args)
          {
              //step3声明一个委托变量mydelegate,且绑定到静态方法DelegateFunction
               MyDelegate mydelegate = new MyDelegate(DelegateFunction);
               Console.Write("请输入数字:");
                 int i = Int32.Parse(Console.ReadLine());
                 //调用委托方法DelegateFunction
                int intResult = mydelegate(i);
                Console.WriteLine("结果是:" + intResult);
                Console.ReadLine();
          }

          //step2定义一个静态方法,返回两数的乘积
          public static int DelegateFunction(int i)
          {
              return i * i;
          }
      }
  } 

  三:运行效果
  

 

 

原创粉丝点击