C# 中的Action Func
2013-08-20 15:10
10 查看
昨天在群里请教了一个问题,学到了不少:
看这个函数的声明
public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, TResult> selector);
感觉有点神奇. 决定研究一下.
看了一下c#高级编程第七版, 重新学习了一下 Action 和 Func
如何定义一个和数组中 Select 类似的函数:
static int get_sum(int x, int y)
{
return x + y;
}
static T test_sum<T>(T x, T y, Func<T, T, T> sum)
{
return sum(x, y);
}
调用方:
int x = test_sum(1, 4, get_sum);
再扩展一下知识,定义一个返回值不同的:
static W test_sum1<T,W>(T x, T y, Func<T, T, W> sum)
{
return sum(x, y);
}
当然你也可以定义N个这参数类型不同的模版参数.
注: 它和c++不同的是不用显式的模版类型., 返回值类型也是在 函数名后.
Action 多播委托:
static void showfun1()
{
Console.WriteLine("show1");
}
static void showfunint(int x)
{
Console.WriteLine(x);
}
Action d1 = showfun1;
d1 += showfun1;
d1();
Action<int> d2 = showfunint;
d2 += showfunint;
这个其实比较简单.
注意Action 不能有返回值, 如果在调用过程中出错,下面的委托不再会调用到.
看这个函数的声明
public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, TResult> selector);
感觉有点神奇. 决定研究一下.
看了一下c#高级编程第七版, 重新学习了一下 Action 和 Func
如何定义一个和数组中 Select 类似的函数:
static int get_sum(int x, int y)
{
return x + y;
}
static T test_sum<T>(T x, T y, Func<T, T, T> sum)
{
return sum(x, y);
}
调用方:
int x = test_sum(1, 4, get_sum);
再扩展一下知识,定义一个返回值不同的:
static W test_sum1<T,W>(T x, T y, Func<T, T, W> sum)
{
return sum(x, y);
}
当然你也可以定义N个这参数类型不同的模版参数.
注: 它和c++不同的是不用显式的模版类型., 返回值类型也是在 函数名后.
Action 多播委托:
static void showfun1()
{
Console.WriteLine("show1");
}
static void showfunint(int x)
{
Console.WriteLine(x);
}
Action d1 = showfun1;
d1 += showfun1;
d1();
Action<int> d2 = showfunint;
d2 += showfunint;
这个其实比较简单.
注意Action 不能有返回值, 如果在调用过程中出错,下面的委托不再会调用到.
相关文章推荐
- 委托,C#本身的委托(Action Func)
- 在C#中用最简洁有效的代码执行存储过程并返回数据
- 在C#.net中操作XML
- 抓取当前界面上任意控件图像的C#代码
- C#设计模式(10)-Adapter Pattern
- CMPP SP端 C# 实例 (转)
- 在C#中取得指定长度的字符串
- Microsoft Visual C# 2005 Express Edition Programming for the Absolute Beginner
- c# 类的public private internal protected的区别
- 学习Asp.Net、C#好网站
- 【转】用C#编写ActiveX控件(三)
- c# 迭代器 与 IEnumerable 与 foreach循环
- C#获取汉字拼音
- C# 运算符
- 数据结构(C#版)概念整理
- listview[C#]如何获得多行数据,将其放入数据库中
- 新旧图幅号转换公式及示例代码(C#)
- C# 插件式程序开发
- 快速了解c#中的索引器
- C# 多线程之新线程延时执行