C#中的委托 一看即明
1.在VS中创建一个控制台应用程序。
2.见Program.cs代码,代码中有清晰的注释。这里把委托和类作比较,一看就明白了。如下:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace DelegateStudy
- {
- class Program
- {
- //声明一个方法,只有一个int类型的参数,有int类型的返回值,备用
- public static int Add3(int age)
- {
- age = age + 3;
- return age;
- }
- //定义一个类,类是一种类型,这个新类型的名称是Person
- //类用于存储数据
- class Person
- {
- public string Name;
- public int Age;
- public Person(){
- this.Name = "xuanwuziyou";
- this.Age = 20;
- }
- public static int Add1(int age)//静态方法
- {
- age++;
- return age ;
- }
- public int Add2(int age)//实例方法
- {
- age = age + 2;
- return age ;
- }
- }
- //定义一个委托,委托也是一种类型,这个新类型的名称是DelegatePerson
- //委托用于存储方法。这个委托可以存储这样的方法:只有一个int类型的参数,有int类型的返回值
- delegate int DelegatePerson(int age);
- static void Main(string[] args)
- {
- //声明一个Person类型的类对象
- Person person;
- //构造函数给类的对象赋值
- person = new Person();
- //调用类的对象
- var calssAge = person.Age;
- Console.WriteLine("person.Age : " + calssAge); //20
- //声明一个DelegatePerson类型的委托变量
- DelegatePerson delegatePerson;
- //把符合规定的方法赋给委托变量
- delegatePerson = Person.Add1; //委托可接受类的静态方法
- delegatePerson += person.Add2; //委托可接受类的实例方法
- delegatePerson += Add3; //委托可接受公共定义方法
- delegatePerson -= Person.Add1; //可从委托的方法列表中删去已添加的方法
- //调用委托变量(即调用委托里保存的方法列表)
- //委托中的方法按顺序执行,委托的返回值就是其最后一个方法的返回值:先调person.Add2( 20 ),调Add3( 20 )
- var deldegateAge = delegatePerson(20);
- Console.WriteLine("delegatePerson(20) : " + deldegateAge); //23
- }
- }
- }
3.输出结果:
4.补充说明:
委托的初始赋值,还可以用lambda表达式方式: delegatePerson = x => x + 10;
posted on 2017-06-08 15:55 alex5211314 阅读(160) 评论(0) 编辑 收藏 举报