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

C#-初识委托

2015-09-16 00:21 483 查看
1、委托是C#一个比较好的设计,委托后,能将C#中的方法作为参数传递到函数中去,在我们的生活中,有时我们需要在某个特定的时间去执行某些任务,例如去学校骑自行车去,乘汽车。有时我们我们只需要写两个方法来表示骑自动车,乘汽车,在设计个函数来传递我们前面的方法来执行,达到精简代码的效果。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Basic
{
/*********************************************************************
* 委托需要关键字delegate定义
* 委托的方法需要传递的参数和委托要一样
* 委托方便的使方法作为参数传递到委托中去执行。对于代码的封装很有好处
*
* ******************************************************************/
// 直接在命名空间下定义委托
public  delegate void Select_thing(string select);

class student_select
{
// 属性
private Select_thing _select;

// 委托将要依附的属性
public Select_thing aaa
{
get
{
return _select;
}
set
{
_select = value;
}
}
// 将要委托的方法,参数要和委托定义的要一样,在这里面都是string
public void print_select_thing(string select)
{
Console.WriteLine("your select1 is :{0}", select);
}
// 将要委托的方法,参数要和委托定义的要一样,在这里面都是string
public void print_select_thing_2(string select)
{
Console.WriteLine("your select2 is :{0}", select);
}
}
class Program
{
static void Main(string[] args)
{

student_select select = new student_select();
select.aaa = new Select_thing(select.print_select_thing);
select.aaa("每一天!");
select.aaa = new Select_thing(select.print_select_thing_2);
select.aaa("每二天!");

Console.Read();
}
}
}

![执行的效果:](http://img.blog.csdn.net/20150916002100567)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: