您现在的位置是:主页 > news > 吉林省舒兰市建设银行网站/百度之家

吉林省舒兰市建设银行网站/百度之家

admin2025/5/23 19:22:23news

简介吉林省舒兰市建设银行网站,百度之家,网站建设与管理好学吗,株洲营销型网站建设本篇内容: 1.自动属性 2.隐式类型 3.对象初始化器和集合初始化器 4.匿名类型 5.扩展方法 6.Lambda表达式 1.自动属性 使用: class Student {public string Name { get; set; }public int Age { get; set; } } 编译后,查看IL语言 CLR 为我们生…

吉林省舒兰市建设银行网站,百度之家,网站建设与管理好学吗,株洲营销型网站建设本篇内容: 1.自动属性 2.隐式类型 3.对象初始化器和集合初始化器 4.匿名类型 5.扩展方法 6.Lambda表达式 1.自动属性 使用: class Student {public string Name { get; set; }public int Age { get; set; } } 编译后,查看IL语言 CLR 为我们生…

本篇内容:

1.自动属性

2.隐式类型

3.对象初始化器和集合初始化器

4.匿名类型

5.扩展方法

6.Lambda表达式

1.自动属性

使用:

class Student
{public string Name { get; set; }public int Age { get; set; }
}

编译后,查看IL语言

image

CLR 为我们生成了,私有字段(.field)和对应的共有属性语法(get_Name(),set_Name(string))

本质:微软为我们提供了“语法糖”,帮助程序员减少代码

2.隐式类型

使用:

static void Main(string[] args)
{var name = "张三";var stu = new Student();stu.Name = name;
}

编译后,查看源代码

image

在编译的时候,根据“=”右边的类型,推断出var的类型,所以在初始化时,var类型就已经确定了

3.对象初始化器和集合初始化器

static void Main(string[] args)
{List<Student> listStu = new List<Student>(){new Student() {Age = 1, Name = "张三"},new Student() {Age = 2, Name = "李四"},new Student() {Age = 3, Name = "王五"}};Dictionary<int, string> dicStu = new Dictionary<int, string>(){{1, "张三"},{2, "李四"}};
}

编译后,查看源码

image

本质:编译器为我们实例化了集合,并创建了集合元素对象,再设置给集合

4.匿名类型

a.匿名类

定义:

static void Main(string[] args)
{var stu = new{Id = 1,Name = "张三",Age = 18};
}

编译后,查看IL代码

image

  发现编译器,为我们生成了一个类。这个类有一个 无返回值,带有对应参数的构造函数

image

b.匿名方法:

定义:

static void Main(string[] args){DGSayHi dgHi = delegate { Console.WriteLine("你好啊"); };dgHi();Console.ReadKey();}

编译后,查看IL语言

image

在看看这个方法

image

得出结论:编译器会为每一个匿名方法,创建一个私有的 静态的 方法,再传给委托对象使用

5.扩展方法

定义:静态类,静态方法,this关键字

static class StuExtention
{public static void SayHi(this Student stuObj){Console.WriteLine(stuObj.Name+",你好啊");}
}

使用

static void Main(string[] args)
{Student stu = new Student(){Age = 1,Name = "张三"};stu.SayHi();Console.ReadKey();
}

6.Lambda表达式

使用:

static void Main(string[] args)
{//匿名方式DGSayHi dgHi = delegate { Console.WriteLine("你好啊"); };//Lambda语句Action dgHi2 = () => { Console.WriteLine("我是Lambda语句,语句可以直接执行"); };//Lambda表达式Action dgHi3 = () => Console.WriteLine("我是Lambda表达式");dgHi();dgHi2();dgHi3();Console.ReadKey();
}

转载于:https://www.cnblogs.com/kimisme/p/4442858.html