委托和匿名方法、lambda表达式

本文介绍了 C# 中的委托概念及其使用方法,包括基本的委托定义与实例化、匿名方法的使用、Lambda 表达式的应用,以及泛型委托的实现。通过具体代码示例展示了如何利用委托来简化代码并提高灵活性。

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

CODE:

using System;

namespace CsDev
{
    delegate void delTest(string a);//委托定义
    delegate void delTest1(int a,params int[] b);
     public class c2
     {
         void testMethod(string a)
         {
             Console.WriteLine("执行委托方法1 "+a);
         }

         public static void Main()
         {
             c2 c = new c2();
             delTest d = c.testMethod;//方法绑定到委托方法列表

             //使用匿名方法形成组合委托
             d += delegate
             {
                 Console.WriteLine("匿名方法! ");
             };
             d("测试委托");
             Console.WriteLine();
             delTest1 d1 = delegate(int a, int[] b)
             {
                 Console.WriteLine("多参数委托方法:");
                 Console.WriteLine(a);
                 foreach (var v in b)
                     Console.Write("{0} ", v);
             };
             d1(5,new int[]{1,2,3,4,5});

             Console.ReadKey();
         }
     }
}

输出:

执行委托方法1 测试委托
匿名方法!


多参数委托方法:
5
1 2 3 4 5


using System;

namespace CsDev
{
    delegate int delTest(int a);//委托定义
     public class c2
     {
         public static void Main()
         {
             c2 c = new c2();
             delTest d;//声明委托变量

             //匿名方法
             d = delegate{ return 3 + 5;};
             
             Console.WriteLine(d(0));
             //lambda表达式
             delTest d1 = a =>a*a;
             Console.WriteLine(d1(5));

             Console.ReadKey();
         }
     }
}

输出:

8

25


泛型委托:

using System;

namespace CsStudy
{
    delegate R MyDel<T, R>(T value);//泛型委托
    class Per
    {
        static public int Print(string s)
        {
            Console.WriteLine(s);
            return 10;
        }
    }

    class Program
    {
        static void Main()
        {
            var myDel = new MyDel<string, int>(Per.Print);
            Console.WriteLine(myDel("Hello"));
            Console.ReadKey();
        }
    }
}

输出:

Hello
10


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值