您的位置:首页 > 编程语言 > C#

C#如何创建一个简单委托。

2016-04-06 21:22 441 查看
委托和类一样,是一种用户自定义的类型。

delegate void PrintFunction();

class Test

{
public void Print1()
{
Console.WriteLine("Print1 -- instance");
}

public static void Print2()
{
Console.WriteLine("Print2 -- static");
}

}

class Program

{
static void Main()
{
Test t = new Test();
//创建一个测试类实例。
PrintFunction pf;           //创建一个空委托。

pf=t.Print1;                //实例化并初始化该委托。

//给委托增加3个另外的方法。
pf+=Test.Print2;
pf+=t.Print1;
pf+=Test.Print2;
//现在,委托含有4个方法。

if( null != pf)   //确定委托中有方法。
  pf();
else
Console.WriteLine("Delegate is empty");
}

}

这段demo输出的结果为:

Print1 -- instance

Print2 -- static

Print1 -- instance

Print2 -- static

创建有返回值的委托。

Delegate int MyDel();       //声明有返回值的方法。

class MyClass

{
int IntValue=5;
public int Add2(){IntValue+=2;return IntValue;}
public int Add3(){IntValue+=3;return IntValue;}

}

class Program

{
static void Main()
{
MyClass mc=new MyClass();
MyDel mDel=mc.Add2;                               //创建并初始化委托。
mDel+=mc.Add3;
//增加方法。
mDel+=mc.Add2; 
//增加方法。
Console.WriteLine("Value:{0}",mDel());
}

}

这段demo的结果为:

Value:12

调用带有引用参数的委托。

delegate void MyDel(ref int X);

class MyClass

{
public void Add2(ref int x){x+=2;}
public void Add3(ref int x){x+=3;}
static void Main()
{
MyClass mc=new MyClass();

MyDel mDel=mc.Add2;
mDel+=mc.Add3;
mDel+=mc.Add2;

int x=5;
mDel(ref x);

Console.WriteLine("Value:{0}",x);
}

}

demo的输出结果为:

Value: 12
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: