很久之前转载的,http://blog.youkuaiyun.com/Joyhen/article/details/9699739
今天一个函授式写法的多层嵌套Func搞的头晕,索性回忆下。零碎的代码如下:
public delegate int MyDelegate(int a, int b);
public static int function(int a, int b) { return a + b; }
static void Main(string[] args) {
MyDelegate delfun = new MyDelegate(function);
MyDelegate delkk = delegate(int a, int b) { return a + b; }; //a,b参数不能推断
MyDelegate lambdakk = (a, b) = >a + b; //a,b参数可以根据MyDelegate来推断
Func < int,int,int > funkk = (a, b) = >a + b; //a,b参数可以根据Func的参数来推断
int result = delfun.Invoke(1, 2); //delfun(1, 2);
Console.WriteLine(result);
Console.WriteLine(lambdakk(1, 2));
Console.WriteLine(lambdakk(1, 2));
Console.WriteLine(funkk(1, 2));
Func < double,double > myfunc = (x) = >2.0 * x * x - 0.5 * x;
Console.WriteLine(myfunc(1)); //1.5
//or
Console.WriteLine((myfunc = (x) = >2.0 * x * x - 0.5 * x)(1)); //1.5
//阶层函数
Func<Func< int,int >,Func< int,int >> F = factorial = >n = >n == 0 ? 1 : n * factorial(n - 1);
//一个参数的括号可以省略
//Func<int, Func<int>> fa = (x) => () => x * 3;
Func < int,Func < int >> fa = x = >() = >x * 3;
//Func<int, Func<int, int>> fb = (x) => (y) => x * y;
Func < int,Func < int,int >> fb = x = >y = >x * y;
Console.WriteLine("fa:{0}, fb:{1}", fa(10)(), fb(10)(5)); //30,50
Console.ReadKey();
}
Func<object, string> fn = x => PrintTaskObjectState(x);
//Task<string> taskWithInActualMethodAndState = new Task<string>(new Func<object, string>(PrintTaskObjectState),
//Task<string> taskWithInActualMethodAndState = new Task<string>(fn, "This is the Task state, could be any object");
Task<string> taskWithInActualMethodAndState = new Task<string>(x => PrintTaskObjectState(x), "This is the Task state, could be any object");
private static string PrintTaskObjectState(object state)
{
Console.WriteLine(state.ToString());
return "***WOWSERS***";
}