C# 委托和方法

委托是一种特殊的引用类型,它将方法也作为特殊的对象封装起来,从而将方法作为变量或参数进行传递

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace ConsoleApplication1
 7 {
 8     delegate void DualFunction(double x,double y);
 9     class Program
10     {
11         static void Main()
12         {
13             DualFunction fun1;
14             double a = 2.5, b = 2;
15             Console.WriteLine("请选择函数(加0减1乘2除3):");
16             int i = int.Parse(Console.ReadLine());
17             if (i == 1)
18                 fun1 = new DualFunction(Sub);
19             else if (i == 2)
20                 fun1 = new DualFunction(Mul);
21             else if (i == 3)
22                 fun1 = new DualFunction(Div);
23             else
24                 fun1 = new DualFunction(Add);
25             fun1(a, b);
26             Console.ReadLine();
27         }
28         static void Add(double x,double y)
29         {
30             Console.WriteLine("{0}+{1}={2}", x, y, x + y);
31         }
32         static void Sub(double x,double y)
33         {
34             Console.WriteLine("{0}-{1}={2}", x, y, x - y);
35         }
36         static void Mul(double x,double y)
37         {
38             Console.WriteLine("{0}*{1}={2}", x, y, x * y);
39         }
40         static void Div(double x,double y)
41         {
42             Console.WriteLine("{0}/{1}={2}", x, y, x / y);
43         }
44     }
45 }
View Code

DaulFunction fun1=new DualFunction(Sub);

DualFunction fun1=Sub;//这两种方式也行

还可以将委托对象放在数组中  比如

static void Main()
{
DualFunction[] funs = new DualFunction[] { Add, Sub, Mul, Div };
double a=2.5, b=2.0;
Console.WriteLine("请选择函数(加0减1乘2除3):");
int i = int.Parse(Console.ReadLine());
funs[i](a, b);
Console.ReadLine();
}

一个委托对象还可以封装多个方法   委托对象的合并和删除  比如DualFunction fun1 = funs[1] + funs[2];

 

posted @ 2015-05-20 00:11  docyard  阅读(842)  评论(0编辑  收藏  举报