C# 委托和方法

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

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace ConsoleApplication1
{
delegate void DualFunction(double x,double y);
class Program
{
static void Main()
{
DualFunction fun1;
double a = 2.5, b = ;
Console.WriteLine("请选择函数(加0减1乘2除3):");
int i = int.Parse(Console.ReadLine());
if (i == )
fun1 = new DualFunction(Sub);
else if (i == )
fun1 = new DualFunction(Mul);
else if (i == )
fun1 = new DualFunction(Div);
else
fun1 = new DualFunction(Add);
fun1(a, b);
Console.ReadLine();
}
static void Add(double x,double y)
{
Console.WriteLine("{0}+{1}={2}", x, y, x + y);
}
static void Sub(double x,double y)
{
Console.WriteLine("{0}-{1}={2}", x, y, x - y);
}
static void Mul(double x,double y)
{
Console.WriteLine("{0}*{1}={2}", x, y, x * y);
}
static void Div(double x,double y)
{
Console.WriteLine("{0}/{1}={2}", x, y, x / y);
}
}
}

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];

上一篇:number_format


下一篇:template template parameter