delegate details
来源:互联网 发布:腾讯游戏mac版 编辑:程序博客网 时间:2024/05/01 14:45
The runtime supports reference types called delegates that serve a purpose similar to that of function pointers in C++. In another word, A delegate is a reference type which is similar to function pointer. It can represent both static and instance methods. And delegates are secure, verifiable, and type safe.
Since I’ve learnt function pointers, I’d like to express the delegates in the way what I think. By this way, we can define a method whose parameter is also a method, or exactly a method name. This makes expansibility to the code. A delegate looks like a class. In fact, it will be compiled to a class by the compiler. Yep, delegate is a type.
using System;
using System.Collections.Generic;
using System.Text;
namespace myDelegate
{
public delegate void Move(string action);
class Test
{
private static void Bird(string action)
{
Console.WriteLine("Bird can " + action);
}
private static void Duck(string action)
{
Console.WriteLine("Duck can " + action);
}
private static void Dog(string action)
{
Console.WriteLine("Dog can " + action);
}
private static void moveTest(string action, Move Acter)
{
Acter(action);
}
static void Main(string[] args)
{
moveTest("fly", Bird);
moveTest("swim", Duck);
moveTest("run", Dog);
Console.ReadLine();
}
}
}
There is another choice. We can avoid using moveTest() and call the methods of Bird(),Duck() and Dog() by delegate.
static void Main(string[] args)
{
Move m;
m = Bird; //eluvate
m += Duck; //syntax banding
m += Dog; //syntax banding
m("eat");
Console.ReadLine();
}
Pay attention here. The first”=”is for eluvation, and the next”+=”is a syntax of banding. If “+=”takes the place of the first “=”,errors will happen during the compiling time. Is there any way to avoid the danger? Of course,with a little modification, the code will be all right in any case. We code like this:
Move n = new Move(Bird);
n += Duck;
n("shout");
// or like this:
Move d = new Move();
d +=Bird; //syntax banding here this time
d += Duck; //banding too
d("breathe");
So a delegate is able to have several values or methods.At last, I’ll talk about the accessibility of the delegates. Usually, we set the attribute of the delegates as private. In this condition,we can easily keep them from been changed by the customer side. Namely, we would better not use public to declare a delegate.
- delegate details
- details
- delegate
- delegate
- Delegate
- delegate
- Delegate
- Delegate
- Delegate
- Delegate
- delegate
- Delegate
- Delegate
- Delegate
- Delegate
- delegate
- Delegate
- delegate
- 创建动态数据输入用户界面
- Java程序类加载完全揭密
- 使用 Windows Mobile 5.0 中的图片、视频和照相机
- 如果说编程语言是一种宗教
- 转:Linux对I/O端口资源的管理
- delegate details
- HP Proliant 系列服务器使用 SmartStart 光盘配置阵列卡过程
- 通过 Active Directory 管理自定义外壳程序
- ProLiant/tc 系列和 HP BladeSystem 服务器 - 服务器到货后开机没有显示如何处理
- 每日IN语(2009-01-12)喝醉了我谁也不服
- 轻松得到适用于C# ADO.NET的各种数据库连接字符串
- 惨,阑尾发炎输液了,难道还得挨一刀?
- IVR(互动式语音应答(IVR,Interactive Voice Response))
- 怎么用SQL语句取出随机的记录?