• delegate、Func、Action几个常用手法


    委托是我们C#开发当中使用频率非常的高一个手段,好处我就不列举了。

    委托早期版本中只有delegate,后期版本有了Func(有返回值)和Action(无返回值)两委托方法。

    我这里将列举它们三个常用的表现方式,还是老规矩上代码:

    class Program
        {
            private delegate int GetSum(List<Product> list); // First Definition Delegate
            static void Main(string[] args)
            {
                //C# delegate
    
                List<Product> list = new List<Product>()
                {
                        new Product{ProductName="Iphone4s", Price=3000},
                    new Product{ProductName="Iphone5",Price=4000},
                    new Product{ProductName="Ipad4",Price=3500}
                };
                GetSum s = GetTotal;
                Console.WriteLine(s(list));
    
                //C# Func
    
                //Method A
                Func<List<Product>, int> func = GetTotal;
                Console.WriteLine(func(list));
    
                //Method B
                Func<List<Product>, int> func1 = delegate(List<Product> listA)
                {
                    
                    return listA.Sum(p => p.Price);
                };
                Console.WriteLine(func1(list));
                
                //Method C
                Func<List<Product>,int> func2=listB=>{
    
                    return listB.Sum(p => p.Price);
                };
                Console.WriteLine(func2(list));
    
                //C# Action
    
    
                Action<List<Product>> action = listC =>
                {
                    listC.ForEach(p => Console.WriteLine(p.Price));
                };
    
                action(list);
                Console.Read();
            
            }
    
            public static  int GetTotal(List<Product> list)
            {
                return list.Select(p => p.Price).Sum();
            }
        }
    
        public class Product
        {
            public string ProductName{get;set;}
            public int Price{get;set;}
        }
  • 相关阅读:
    概率论
    英语单词每日学习
    网上学习新课程--使用开发板动手进行uboot、内核以及驱动移植
    csdn专家主页
    material of DeepLearning
    I2C协议
    SVN appears to be part of a Subversion 问题心得
    @清晰掉 各种类型32位与64位下各类型长度对比
    超级方便的linux命令手册
    HTTP协议详解(转)
  • 原文地址:https://www.cnblogs.com/flyfish2012/p/3234555.html
Copyright © 2020-2023  润新知