C# 匿名函数

1、匿名函数

没有名字的函数,主要是配合委托和事件进行使用,脱离委托和事件是不会使用匿名函数的

2、基本语法

delegate (参数列表){
      //函数逻辑
};

何时使用?

(1)函数中传递委托参数时

(2)委托和事件赋值时

3、使用

(1)无参无返回

Action a = delegate () {
    Console.WriteLine("匿名函数");
};
a();

(2)有参 

Action<int> a = delegate (int value) {
    Console.WriteLine(value);
};
a(100);

(3)有返回值

直接return,返回值自动识别

Func<string> a = delegate () {
    return "返回值匿名函数";
};
Console.WriteLine(a());

(4)一般情况会作为函数参数传递,或者作为函数返回值

class Test {
    public Action action;

    // 作为参数传递
    public void DoSomeThing(int a, Action action) {
        Console.WriteLine(a);
        action();
    }

    // 作为返回值 
    public Action GetFun() {
        return TestRet;
    }

    public void TestRet() {

    }

    // 或者一步到位
    public Action GetFun2() {
        return delegate () {
            Console.WriteLine("作为返回值的匿名函数");
        };
    }
}

作为参数传递的调用

Test t = new Test();
// 方式一
t.DoSomeThing(100, delegate () {
    Console.WriteLine("作为参数传递的匿名函数");
});

// 方式二
Action ac = delegate () {
    Console.WriteLine("作为参数传递的匿名函数");
};
t.DoSomeThing(100, ac);

作为返回值的调用

// 方式一
Action ac = t.GetFun2();
ac();
// 方式二
t.GetFun2()();

4、匿名函数的缺点

添加到委托或事件容器中后,无法单独移除,只能直接清空

 注意!!!匿名函数会改变变量的生命周期,例如:

static Func<int, int> TestFun(int v) {
    return delegate (int i) {
        return i * v;
    };
}

然后进行调用

Func<int, int> fun = TestFun(2);
Console.WriteLine(fun(3))

可以发现,v的生命周期在TestFun()结束时没有停止

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值