DEV Community

Alex
Alex

Posted on

.NET Learning Notes: C# new grammer(before C#10)

1、顶级语句(C#9):https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/program-structure/top-level-statements
同一个项目只有一类里有顶级语句,编译后默认没有namespace。
2、全局Using指令(C#10):https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive
将global修饰符添加到using前,这个命名空间就应用到整个项目,不用重复using。
通常创建一个专门用来编写using代码的C#文件
如果csproj中启用了ImplicitUsing这个属性,编译器会自动隐式添加对System、System.Linq等常用命名空间的引入。
3、Using资源管理问题:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/using
实现了IDisposible接口的对象可以用using进行管理,如果代码离开using范围,自动释放对应资源。如果一段代码中有很多非托管资源需要被释放的话,代码中就会存在多个嵌套的using语句。
C#8,using声明,在实现了Idisposable/IAsyncDisposalbe接口的类型的变量声明前加上using,当代码执行离开变量的作用域时,对象就会被释放。
4、文件范围的命名空间声明:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/namespace
在之前的版本中,类型必须定义在namespace中;
5、可空引用类型:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-reference-types
问题:如果不注意检查引用类型变量是否可空,出现空指针异常。
在引用类型后添加?修饰符来声明这个类型是可空的。对于没有添加?修饰符的引用类型的变量,如果编译器发现存在为这个变量赋值null的可能性的时候,编译器会发出警告信息。
6、record类型:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record
C#中的==和Equals默认判断两个变量指向的是否是同一个对象,即使两个对象内容完全一样,也不相同。可以通过重写Equals方法、重写==运算符来解决这个问题,不过需要开发人员写很多冗余代码。
在C#9中增加了record类型的语法,编译器会自动生成Equals、gethashCode等方法。
Record:编译器会根据类型中的属性定义,自动为类生成包含全部属性的构造方法,也会生成ToString方法和Equals等方法。record本质上就是一个普通类。record数据类型提供了所有属性赋值的构造方法,所有属性都是只读的,而且对象可以进行值相等比较,并且提供了可读性强的toString返回值。

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post