木头象

人生如棋局

导航

从函数指针到代理(C#代理入门)


// c中的函数指针,可能更好理解

#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"

int (* Test) (int l); //定义函数指针


//以下定义了两个处理函数,程序会根据情况调用不同的过程

int Add(int t)
{
 return t+ t;
}

int Mut(int t)
{
 return t*t;
}


//把函数做参数
 int test2(int t,int (* p) (int ))
{
 return p(t);
}


int main(int argc, char* argv[])
{
 char input[8];
 printf("Please Input a Number!\n");
 scanf("%s",input);
 int t = atoi(input);
 int p;

 //大于10,此指针指向Add()
 if(t > 10)
  Test = Add;
 //小于10,此指针指向Mut()
 else
  Test = Mut;

 //通过指针调用
 p =  Test(t);

 printf("The Result is %d",p);

 if(t > 10)
  p = test2(t,Add);
 //小于10,此指针指向Mut()
 else
  p = test2(t,Mut);

 return 0;
}

// c# 中的代理,和函数指针其实一样,不过扩展了一些功能而已 :)
using System;

namespace tdele
{
 ///


 /// Class2 的摘要说明。
 ///

 public class Class2
 {
  public delegate int Test(int t);  //申明一个代理(函数指针)

  public event Test e;    // 触发词函数的事件

  //以下定义了两个处理函数,程序会根据情况调用不同的过程
  public int Add(int t)
  {
   return t + t;
  }
  public int Mut(int t)
  {
   return t * t;
  }
  public Class2()
  {
   //
   // TODO: 在此处添加构造函数逻辑
   //


  }

  public void test()
  {
  
   int t = Int32.Parse(Console.ReadLine());
   
   //大于10,事件e的处理函数用Add()
   if(t > 10)
    this.e += new Test(Add);
   //小于10,Mut()
   else
    this.e += new Test(Mut);

   //引发一个事件,得到处理结果
   int p = e(t);

   //打印输出
   Console.Write("The Result is {0}",p);

   if(t > 10)
    p = test(t,new Test(Add));
    //小于10,Mut()
   else
    p = test(t,new Test(Mut));

  
   //打印输出
   Console.Write("The Result is {0}",p);
 
  }
  public int test(int i,Test p)
  {
  
   return p(i); 
  }


  public static void Main()
  {
   Class2 t = new Class2();
   t.test();
  }
 }
}

(03年4月一回贴, 测试发贴)

posted on 2004-02-02 11:23  木头象  阅读(4585)  评论(0编辑  收藏  举报