Func和委托零碎代码

本文作者通过回顾一段多层嵌套Func的复杂代码,探讨Func和委托在编程中的应用,帮助读者理解这两种概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很久之前转载的,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***";
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值