委托,匿名方法与LAMDA表达式

1.委托

在.NET中,委托使用得非常频繁,委托是方法的指针。委托可以通过指向不同的方法来实现灵活调用。委托的使用方式如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegateAnonymousMethodLamdaExpression
{
    delegate int ChangeValue(int input);

    class Program
    {
        static ChangeValue changeValue1;

        static ChangeValue changeValue2;

        static void Main(string[] args)
        {
            changeValue1 = Change1;
            Console.WriteLine(changeValue1(10));

            changeValue1 = Change2;
            Console.WriteLine(changeValue1(10));

            changeValue2 += Change3;
            changeValue2 += Change4;
            changeValue2(20);

            Console.ReadKey();
        }

        static int Change1(int x)
        {
            return x + 5;
        }

        static int Change2(int x)
        {
            return x + 10;
        }

        static int Change3(int x)
        {
            Console.WriteLine (x + 5);
            return x + 5;
        }

        static int Change4(int x)
        {
            Console.WriteLine(x + 10);
            return x + 10;
        }
    }
}

输出结果:

2.匿名方法

匿名方法是使用delegate关键字来使用的,下面的例子就是使用匿名方法的例子。

ChangeValue cv = delegate(int x) { return x * 5; };
Console.WriteLine(cv(50));

匿名方法使用有一定的局限性,就是逻辑不宜过长。

3.LAMDA 表达式

LAMDA表达式非常简洁,能够作为匿名方法的替代。

ChangeValue myDel = x => x * 5;
Console.WriteLine(myDel(50));

这就是委托,匿名方法和LAMDA表达式的使用。

源代码下载:http://download.csdn.net/detail/afandaafandaafanda/8320033



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值