C#进阶学习第十三天

1.匿名类型

没有指明类型的类型,通过隐式类型和对象初始化器创建了一个未知类型的对象,减少了代码

1.定义匿名类型对象: 只能包含只读属性,不能修改

    var p = new{Name = "libiao",Age = 23};
    Console.WriteLine ("姓名:"+p.Name +"年龄:"+p.Age);

2.定义匿名类型数组:

    var a = new [] {  new{Name = "li",Age = 23},
                      new{Name = "li",Age = 23},
                      new{Name = "li",Age = 23},}; //类型保持一致
    foreach (var item in a) 
    { Console.WriteLine ("姓名:"+item.Name +"年龄:"+item.Age);}

2.Lanbda表达式

可以理解为一个匿名方法,=>左边为参数,右边为表达式或语句块,也会形成闭包

1.表达式lambda 2.语句lambda

    public delegate int  mydele(int a,int b);
    public delegate int  mydele2(int a);
    public delegate void mydele3();
    public delegate int  mydele4(int a,string b);
     mydele   tt =(x,y) =>x+y;             //类型可以省略,根据传参自动识别
     mydele2  t2 =x=>++x;                  //当只有一个参数,括号随意,多个参数,括号必加
     mydele3  t3 =()=>{console.writeline(“hello”)};    //当无参时,括号不能省略
     mydele4  t4 =(int x,string s) => s.Length >x;     //无法确定类型,要显示指定类型

2.标准的输入参数

	Func<int,int> d1= a => a + a;            //两个参数  Console.WriteLine (d1(3));
	Func<int ,int ,int> d2= (c,d)=>c+d;      //三个参数  Console.WriteLine (d2(4,5));
	Func<int ,int ,bool> d2= (c,d)=>c==d;    //三个参数  Console.WriteLine (d2(4,5));        
      自定义一个系统提供的        //自定义Console.WriteLine (d3(4));  True or false
    public delegate T mydelega<V,T>(T a); 
    mydelega<int ,int> d3 = e => e * e; 
         
    //sort方法中使用lambda表达式大小排序
    //多权重排序,根据规则的权重优先权按某个规则排序
   	l.Sort((x, y) => x.sortByAge(y) * 4 + x.sortByChinese(y) * 2 + x.sortByMath(y)*1);
    public int sortByAge(Student anotherStudent)
	{
	   int result = this.Age - anotherStudent.Age;
       return result == 0 ? 0 : (result > 0 ? 1 : -1);
	}
	public int sortByChinese(Student anotherStudent)
	{
	   int result = (int)(this.Chinese - anotherStudent.Chinese);
	   return result == 0 ? 0 : (result > 0 ? 1 : -1);  
	}

猜你喜欢

转载自blog.csdn.net/JingDuiTell/article/details/88785439