using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//调用带返回值的委托。如果方法列表中有多个方法,
//则最后一个方法的返回值就是委托的返回值,其他方法的返回值都被忽略。
namespace Examples
{
delegate int MyDel();
// 声明一个带返回值的委托
class MyClass
{
int IntValue = 0;
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.Add2;// 创建委托实例.
Console.WriteLine("Value: {0}", mDel());//2
mDel += mc.Add3; // 追加方法到列表
Console.WriteLine("Value: {0}", mDel());
//先运行了一次add2 ,再运行一次add2 add3
mDel += mc.Add2; // 追加方法到列表
//mDel -= mc.Add2;
Console.WriteLine("Value: {0}", mDel());//14
mDel += mc.Add3; // 追加方法到列表
Console.WriteLine("Value: {0}", mDel());
Console.ReadLine();
}
}
}
如上描述如有不懂,或想学习更多技术知识,可以扫码关注麒琳技术栈公众号,欢迎在线咨询