《深入浅出理解C#》 一、使用Comparison进行排序和使用Predicate循环打印、处理未知数据和可选参数及默认值

一、Comparison

Comparison方法定义:比较两个同一类型的方法

代码(委托方法):

public delegate int Comparison<in T>(T x, T y);

sort方法(参数为Comparison):

public void Sort(Comparison<T> comparison);

使用范例:

List<Product> products = Product.GetSampleProducts();
products.Sort((x, y) => x.name.CompareTo(y.name));
foreach (Product product in products)
{
      Console.WriteLine(product);
}

 

二、Predicate

Predicate方法定义:表示定义一组条件并确定指定对象是否符合这些条件的方法

代码(委托方法):

public delegate bool Predicate<in T>(T obj);

Action方法(封装一个方法,该方法只有一个参数并且不返回值):

public delegate void Action<in T>(T obj);

使用范例:

List<Product> products = Product.GetSampleProducts();
Predicate<Product> test = delegate(Product p) { return p.price > 10m; };
List<Product> matches = products.FindAll(test);

Action<Product> print = Console.WriteLine;
matches.ForEach(print);

通过FindAll和ForEach来分解问题,先定义筛选方法,通过FindAll方法查询,再定义一个print行为,通过ForEach方法进行打印

FindAll代码:

public List<T> FindAll(Predicate<T> match);

ForEach代码:

public void ForEach(Action<T> action);

 

三、未知数据、可选参数和默认值

List<Product> products = Product.GetSampleProducts();
foreach (Product product in products.Where(p => p.price == null))
{
     Console.WriteLine(product);
}

public class Product 
{
            public string name{get;private set;}
            //允许为null值
            public decimal? price{get;private set;}

            public Product() { }
            //c#4增加参数默认值
            public Product(string name, decimal? price=null)
            {
                this.name=name;
                this.price=price;
            }

            public static List<Product> GetSampleProducts()
            {
                return new List<Product>
                {
                    new Product(name:"West Side Story",price:9.99m),
                    new Product(name:"Assassins",price:14.99m),
                    new Product(name:"Frogs",price:13.99m),
                    new Product(name:"Sweeney Todd",price:10.99m),
                    new Product(name:"Bney")
                };
            }

            public override string ToString()
            {
                return string.Format("{0}:{1}", name,price);
            }

 }

 

posted @ 2020-07-03 21:20  榕树下的回忆  阅读(1071)  评论(0编辑  收藏  举报