C# 5 in a Nutshell - Delegate
2024-10-01 05:02:44
1. What is delegate in C#?
A delegate is an object that knows how to call a method.
A delegate type defines the kind of method that delegate instances can call. Specifically,
it defines the method’s return type and its parameter types.
The followingdefines a delegate type called Transformer:
delegate int Transformer (int x);
Transformer is compatible with any method with an int return type and a single
int parameter, such as this:
static int Square (int x) { return x * x; }
Assigning a method to a delegate variable creates a delegate instance:
Transformer t = Square;
complete code:
public delegate int Transformer (int x);
class Util
{
public static void Transform (int[] values, Transformer t)
{
for (int i = ; i < values.Length; i++)
values[i] = t (values[i]);
}
} class Test
{
static void Main()
{
int[] values = { , , };
Util.Transform (values, Square); // Hook in the Square method
foreach (int i in values)
Console.Write (i + " "); // 1 4 9
}
static int Square (int x) { return x * x; }
}
最新文章
- CSS float 浮动属性
- HTML DOM 教程
- hive中大表join
- Netty writeAndFlush() 流程与异步
- IOS UITableView下拉刷新和上拉加载功能的实现
- JQUERY与JS的区别
- C++ this 指针
- Linux设置全局代理与yum代理
- org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not a
- Abnormal build process termination--解决IDEA启动web项目报错
- webpack开发环境和生产环境切换原理
- JavaScript基础视频教程总结(071-080章)
- 内置系统账户:Local system/Network service/Local Service 区别
- vim3
- delphi Image 处理
- 源代码下载 作者:王先荣(Xianrong Wang)
- 神经网络 java包
- 用EXCEL批量更改文件名,一个命令就能完成
- Android 修改Camera拍照的默认保存路径
- leetcode-374-Guess Number Higher or Lower(二分查找)