MVC系列学习(一)-新语法
2024-09-08 10:43:34
本篇内容:
1.自动属性 2.隐式类型 3.对象初始化器和集合初始化器 4.匿名类型 5.扩展方法 6.Lambda表达式 |
1.自动属性
使用:
class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
编译后,查看IL语言
CLR 为我们生成了,私有字段(.field)和对应的共有属性语法(get_Name(),set_Name(string))
本质:微软为我们提供了“语法糖”,帮助程序员减少代码
2.隐式类型
使用:
static void Main(string[] args)
{
var name = "张三";
var stu = new Student();
stu.Name = name;
}
编译后,查看源代码
在编译的时候,根据“=”右边的类型,推断出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, "李四"}
};
}
编译后,查看源码
本质:编译器为我们实例化了集合,并创建了集合元素对象,再设置给集合
4.匿名类型
a.匿名类
定义:
static void Main(string[] args)
{
var stu = new
{
Id = 1,
Name = "张三",
Age = 18
};
}
编译后,查看IL代码
发现编译器,为我们生成了一个类。这个类有一个 无返回值,带有对应参数的构造函数
b.匿名方法:
定义:
static void Main(string[] args)
{
DGSayHi dgHi = delegate { Console.WriteLine("你好啊"); };
dgHi();
Console.ReadKey();
}
编译后,查看IL语言
在看看这个方法
得出结论:编译器会为每一个匿名方法,创建一个私有的 静态的 方法,再传给委托对象使用
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();
}
最新文章
- 北京培训记day1
- centos7 使用updatedb和locate命令
- chartjs执行图表
- C# 发送邮件,QQ企业邮箱测试成功
- Latex常用指令学习
- Javascript 添加自定义静态方法属性JS清除左右空格
- Spring注解@Scheduled定时任务
- kuangbin_ShortPath I (POJ 2240)
- Linux内核等待队列
- hdoj 1060
- trie树信息抽取之中文数字抽取
- 【攻防实战】SQL注入演练!
- Linux下ifort的安装记录
- Spring整合JMS(三)——MessageConverter介绍
- The SQL Server instance returned an invalid or unsupported protocol version during login negotiatio
- 记一次nginx强制将https请求重定向http
- HtmlControls和Webcontrols命名空间的区别
- CVE-2013-2551
- SqlServer安装时的选项说明
- 【转】【MySQL报错】ERROR 1558 (HY000): Column count of mysql.user is wrong. Expected 43, found 39.
热门文章
- 3.3.5 boolean类型
- 不动点(Fixed Point)
- RabbitMQ-基本概念(一)
- RMI分布式议程服务学习
- windows安装Reids
- 【BZOJ4199&;UOJ131】品酒大会(后缀数组,并查集)
- Parallelized coherent read and writeback transaction processing system for use in a packet switched cache coherent multiprocessor system
- 试来试去,WIN下最简单的WIN API开发工具,Pelles C就好啦
- 如何将PSD批量装换为JPG如何对PSD批量减小体积
- Android开发系列(二十四):Notification的功能与使用方法