当前位置:网站首页>New features of C 10
New features of C 10
2022-07-03 16:48:00 【Dotnet cross platform】
Click on the blue words above
Pay attention to our
( Required for reading this article 15 minute )
We are pleased to announce C# 10 As .NET 6 and Visual Studio 2022 Part of has been released . In this article , We will introduce C# 10 Many of the new features of , These features make your code more beautiful 、 More expressive 、 faster .
read Visual Studio 2022 Announcements and .NET 6 Announcement for more information , Including how to install .
Visual Studio 2022 Notice
https://aka.ms/vs2022gablog
.NET 6
https://aka.ms/dotnet6-GA

Global and implicit usings

using Directives simplify the way you use namespaces .C# 10 Including a new global using Instructions and implicit usings, To reduce the amount of... You need to specify at the top of each file usings Number .
overall situation using Instructions
If the keyword global Appear in the using Before the order , be using For the whole project :
global using System;You can do it globally using Use in instruction using Any function of . for example , Add a static import type and make its members and nested types available throughout the project . If you are in using Alias used in directive , This alias will also affect your entire project :
global using static System.Console;
global using Env = System.Environment;You can put global usage anywhere .cs In file , Include Program.cs Or a specially named file , Such as globalusings.cs. overall situation usings The scope of is the current compilation , It generally corresponds to the current project .
For more information , See global using Instructions .
overall situation using Instructions
https://docs.microsoft.com/dotnet/csharp/languagereference/keywords/using-directive#global-modifier
Implicit usings
Implicit usings The function automatically adds a common global for the type of project you are building using Instructions . To enable implicit usings, Please be there. .csproj Set in file ImplicitUsings attribute :
<PropertyGroup>
<!-- Other properties like OutputType and TargetFramework -->
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>In the new .NET 6 Implicit is enabled in the template usings . Read about... In this blog post .NET 6 More about template changes .
Some specific global using The instruction set depends on the type of application you are building . for example , Implicit of console application or class library usings differ ASP.NET The implicit of the application usings.
For more information , See this implicit usings article .
Blog posts
https://devblogs.microsoft.com/dotnet/announcing-net-6-preview-7/#net-sdk-c-project-templates-modernized
Implicit usings
https://docs.microsoft.com/en-us/dotnet/core/project-sdk/overview#implicit-using-directives

Combining using function

Traditional at the top of the file using Instructions 、 overall situation using Instructions and implicit using Can work well together . Implicit using Allows you to include in your project file the information that is appropriate for the type of project you are building .NET Namespace . overall situation using Directives allow you to include other namespaces , To make them available throughout the project . At the top of the code file using Directives allow you to include namespaces that are used by only a few files in your project .
No matter how they are defined , additional using Instructions will increase the possibility of ambiguity in name resolution . If this happens , Consider adding aliases or reducing the number of namespaces to import . for example , You can set the global using Replace the directive with an explicit at the top of the file subset using Instructions .
If you need to delete through implicit usings The namespace contained , You can specify them in the project file :
<ItemGroup>
<Using Remove="System.Threading.Tasks" />
</ItemGroup>You can also add namespaces , Like they're global using The instructions are the same , You can use Using Add item to project file , for example :
<ItemGroup>
<Using Include="System.IO.Pipes" />
</ItemGroup>
The namespace of the file scope

Many files contain code from a single namespace . from C# 10 Start , You can include namespaces as statements , Followed by a semicolon without curly braces :
namespace MyCompany.MyNamespace;
class MyClass // Note: no indentation
{ ... }He simplified the code and removed the nesting level . Only one file wide namespace declaration is allowed , And it must appear before declaring any type .
More information about file scope namespaces , See the namespace keywords article .
Namespace keyword article https://docs.microsoft.com/dotnet/csharp/languagereference/keywords/namespace

Yes lambda Improvement of expression and method group

We are right. lambda A number of improvements have been made in the syntax and types of . We expect these to be widely useful , And one of the driving schemes is to make ASP.NET Minimal API It's simpler .
lambda The grammar of
https://docs.microsoft.com/dotnet/csharp/whats-new/csharp-10#lambda-expression-improvements
ASP.NET Minimal API
https://devblogs.microsoft.com/dotnet/announcing-asp-net-core-in-net-6/
lambda The natural type of
Lambda Expressions now sometimes have “ natural ” type . This means that compilers can usually infer lambda The type of expression .
up to now , Must be lambda Expression converted to delegate or expression type . in the majority of cases , You will BCL Use overloaded Func<...> or Action<...> One of the delegate types :
Func<string, int> parse = (string s) => int.Parse(s);however , from C# 10 Start , If lambda There is no such “ The target type ”, We will try to calculate a for you :
var parse = (string s) => int.Parse(s);You can hover over... In your favorite editor var parse On , Then check that the type is still Func<string, int>. Generally speaking , The compiler will use the available Func or Action entrust ( If there is an appropriate delegation ). otherwise , It composes a delegate type ( for example , When you have ref Parameters or when there are a large number of parameters ).
Not all lambda Expressions have natural types —— Some just don't have enough type information . for example , Abandoning parameter types will make it impossible for the compiler to decide which delegate type to use :
var parse = s => int.Parse(s); // ERROR: Not enough type info in the lambdalambda Natural types of mean that they can be assigned to weaker types , for example object or Delegate:
object parse = (string s) => int.Parse(s); // Func<string, int>
Delegate parse = (string s) => int.Parse(s); // Func<string, int>When it comes to expression trees , We combined “ The goal is ” and “ natural ” type . If the target type is LambdaExpression Or non generic Expression( The base type of all expression trees ) also lambda With natural delegate type D, We will instead generate Expression<D>:
LambdaExpression parseExpr = (string s) => int.Parse(s); // Expression<Func<string, int>>
Expression parseExpr = (string s) => int.Parse(s); // Expression<Func<string, int>> The natural type of the method group
Method group ( That is, the method name without parameter list ) Now sometimes there are natural types . You can always convert method groups to compatible delegate types :
Func<int> read = Console.Read;
Action<string> write = Console.Write;Now? , If the method group has only one overload , It will have a natural type :
var read = Console.Read; // Just one overload; Func<int> inferred
var write = Console.Write; // ERROR: Multiple overloads, can't chooselambda The return type of
In the previous example ,lambda The return type of an expression is obvious , And inferred . This is not always the case :
var choose = (bool b) => b ? 1 : "two"; // ERROR: Can't infer return typestay C# 10 in , You can go to lambda Specify the explicit return type on the expression , Just like on methods or local functions . The return type precedes the parameter . When you specify an explicit return type , Parameters must be enclosed in parentheses , This way, compilers or other developers won't be too confused :
var choose = object (bool b) => b ? 1 : "two"; // Func<bool, object>lambda Properties on
from C# 10 Start , You can put attributes in lambda On the expression , Just like for methods and local functions . When there are attributes ,lambda The parameter list of must be enclosed in parentheses :
Func<string, int> parse = [Example(1)] (s) => int.Parse(s);
var choose = [Example(2)][Example(3)] object (bool b) => b ? 1 : "two";Just like local functions , If the attribute is in AttributeTargets.Method On the effective , You can apply the attribute to lambda.
Lambda The method of calling is different from methods and local functions , So in the call lambda Properties have no effect . however ,lambdas Properties on are still useful for code analysis , And they can be found by reflection .
structs Of improvement
C# 10 by structs Introduced the function , Can be found in structs ( structure ) Provide better parity between and classes . These new features include parameterless constructors 、 Field initializer 、 Record structure and with expression .
01 Parameterless structure constructor and field initializer
stay C# 10 Before , Each structure has an implicit public parameterless constructor , This constructor sets the fields of the structure to the default value . It is wrong to create a parameterless constructor on a structure .
from C# 10 Start , You can include your own parameterless constructor . If you do not provide , An implicit parameterless constructor will be provided to set all fields to their default values . The parameterless constructor you create in a structure must be public and cannot be partial :
public struct Address
{
public Address()
{
City = "<unknown>";
}
public string City { get; init; }
} You can initialize fields in a parameterless constructor as described above , They can also be initialized through the field or property initializer :
public struct Address
{
public string City { get; init; } = "<unknown>";
}Structures created by default or as part of an array assignment ignore explicit parameterless constructors , And always set the structure members to their default values . More information about parameterless constructors in structures , See structure type .
02 Record structs
from C# 10 Start , Now you can use record struct Definition record. These are similar to C# 9 Introduced in record class :
public record struct Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
}You can continue to use record Define record class , You can also use record Class to clearly illustrate .
Structure already has equal values —— When you compare them , It's by value . Record structure add IEquatable<T> Support and == Operator . Record structure provision IEquatable<T> Custom implementation of to avoid reflection performance problems , And they include recording functions , Such as ToString() Cover .
The record structure can be positional , The main constructor implicitly declares public members :
public record struct Person(string FirstName, string LastName);The parameters of the main constructor become the public automatic implementation properties of the record structure . And record Different types , The implicitly created property is read / Written . This makes it easier to convert tuples to named types . Change the return type from (string FirstName, string LastName) Such tuples are changed to Person Named types can clean up your code and ensure that member names are consistent . It's easy to declare the location record structure and maintain variable semantics .
If you declare a property or field with the same name as the main constructor parameter , No automatic attributes will be synthesized and your .
To create an immutable record structure , Please put readonly Add to structure ( Just as you can add to any structure ) Or will readonly Apply to a single attribute . Object initializers are part of the construction phase where read-only properties can be set . This is just one way to use an immutable record structure :
var person = new Person { FirstName = "Mads", LastName = "Torgersen"};
public readonly record struct Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
}Learn more about record structure in this article .
Record structure
https://docs.microsoft.com/dotnet/csharp/language-reference/builtin-types/record
03 Record Class ToString () Seal modifier on
Record classes have also been improved . from C# 10 Start ,ToString() Methods can include seal Modifier , This prevents the compiler from synthesizing for any derived records ToString Realization .
Learn about... In the records in this article ToString () For more information .
of ToString () For more information
https://docs.microsoft.com/dotnet/csharp/language-reference/builtin-types/record#built-in-formatting-for-display
04 Structures and expressions of anonymous types
C# 10 Support all structures with expression , Including record structure , And anonymous types :
var person2 = person with { LastName = "Kristensen" }; This will return a new instance with a new value . You can update any number of values . Values you do not set will remain the same as the initial instance .
Learn about in this article with For more information
Learn about with For more information
https://docs.microsoft.com/dotnet/csharp/language-reference/builtin-types/record#built-in-formatting-for-display
Interpolation string improvement
When we're in C# When adding an interpolated string to , We always feel that in terms of performance and expressiveness , You can do more with this syntax .
01 Interpolation string handler
today , The compiler converts the interpolated string to a pair of string.Format Call to . This can lead to a lot of distribution —— Packing of parameters 、 Allocation of parameter array , And, of course, the result string itself . Besides , It has no room for maneuver in the meaning of actual interpolation .
stay C# 10 in , We added a library pattern , allow API “ To take over ” Processing of interpolated string parameter expression . for example , consider StringBuilder.Append:
var sb = new StringBuilder();
sb.Append($"Hello {args[0]}, how are you?"); up to now , This will call... With the newly allocated and calculated string Append(string? value) heavy load , Attach it to StringBuilder In a piece of . however ,Append Now there is a new overload Append(refStringBuilder.AppendInterpolatedStringHandler handler), When using an interpolated string as a parameter , It takes precedence over string overloading .
Usually , When you see SomethingInterpolatedStringHandler Parameter type of form ,API The author did some work behind the scenes , To handle the interpolated string more appropriately to meet its purpose . In our Append Example , character string “Hello”、args[0] and “,how are you?” Attach separate to StringBuilder in , This is more efficient and the results are the same .
Sometimes you just want to build strings under certain conditions . One example is Debug.Assert:
Debug.Assert(condition, $"{SomethingExpensiveHappensHere()}");in the majority of cases , Condition is true , The second parameter is not used . however , Each call evaluates all parameters , This unnecessarily slows down the execution speed .Debug.Assert There is now an overload with a custom interpolation string builder , It ensures that the second parameter is not even evaluated , Unless the condition is false .
Last , This is an example of actually changing the string interpolation behavior in a given call :String.Create() Allow you to specify IFormatProvider The expression in the hole used to format the interpolation string parameter itself :
String.Create(CultureInfo.InvariantCulture, $"The result is {result}");You can learn more about interpolating string handlers in this article and in this tutorial on creating custom handlers .
Create a custom handler
https://docs.microsoft.com/dotnet/csharp/languagereference/tokens/interpolated#compilation-of-interpolated-strings
More information about the interpolation string handler
https://docs.microsoft.com/dotnet/csharp/whats-new/tutorials/interpolated-string-handler
02 Constant interpolation string
If all the holes in the interpolated string are constant strings , Then the generated string is now a constant . This allows you to use string interpolation syntax in more places , Example attribute :
[Obsolete($"Call {nameof(Discard)} instead")]Please note that , The hole must be filled with a constant string . Other types , Such as number or date value , Out of commission , Because they are sensitive to culture , And cannot be evaluated at compile time .

Other improvements

C# 10 Many minor improvements have been made to the whole language . Some of them just make C# Work the way you want .
Mix declarations and variables in Deconstruction
stay C# 10 Before , Deconstruction requires all variables to be new , Or all variables must be declared in advance . stay C# 10 in , You can mix :
int x2;
int y2;
(x2, y2) = (0, 1); // Works in C# 9
(var x, var y) = (0, 1); // Works in C# 9
(x2, var y3) = (0, 1); // Works in C# 10 onwardsLearn more in the article on deconstruction .
Improved clear allocation
If you use a value that has not been explicitly assigned ,C# There will be mistakes .C# 10 You can better understand your code and produce fewer false errors . These same improvements also mean that you will see fewer false errors and warnings for empty references .
stay C# 10 New features in the article to learn about C# More information on determining the assignment .
C# 10 New features article in
https://docs.microsoft.com/dotnet/csharp/whats-new/csharp-10#improved-definite-assignment
Extended attribute mode
C# 10 Added extended attribute mode , To make it easier to access nested attribute values in the schema . for example , If we were up there Person Add an address to the record , We can do pattern matching in the following two ways :
object obj = new Person
{
FirstName = "Kathleen",
LastName = "Dollard",
Address = new Address { City = "Seattle" }
};
if (obj is Person { Address: { City: "Seattle" } })
Console.WriteLine("Seattle");
if (obj is Person { Address.City: "Seattle" }) // Extended property pattern
Console.WriteLine("Seattle");The extended attribute pattern simplifies the code and makes it easier to read , Especially when matching multiple attributes .
Learn more about extended attribute patterns in the pattern matching article .
Pattern matching article
https://docs.microsoft.com/dotnet/csharp/languagereference/operators/patterns#property-pattern
Caller expression property
CallerArgumentExpressionAttribute Provides information about the method call context . And others CompilerServices Same property , This property applies to optional parameters . under these circumstances , A string :
void CheckExpression(bool condition,
[CallerArgumentExpression("condition")] string? message = null )
{
Console.WriteLine($"Condition: {message}");
}Pass to CallerArgumentExpression The parameter name of is the name of a different parameter . The expression passed to the parameter as a parameter will be contained in the string . for example ,
var a = 6;
var b = true;
CheckExpression(true);
CheckExpression(b);
CheckExpression(a > 5);
// Output:
// Condition: true
// Condition: b
// Condition: a > 5ArgumentNullException.ThrowIfNull() Is a good example of how to use this property . It avoids having to pass in parameter names by default :
void MyMethod(object value)
{
ArgumentNullException.ThrowIfNull(value);
}Learn about CallerArgumentExpressionAttribute For more information
https://docs.microsoft.com/dotnet/csharp/languagereference/attributes/caller-information#argument-expressions
Feel free to leave a comment below , Tell us your suggestions or ideas , thank you !
边栏推荐
猜你喜欢

QT serial port UI design and solution to display Chinese garbled code

Cocos Creator 2.x 自动打包(构建 + 编译)

Explore Netease's large-scale automated testing solutions see here see here

跟我学企业级flutter项目:简化框架demo参考

Aike AI frontier promotion (7.3)

Cocos Creator 2. X automatic packaging (build + compile)

什么是质押池,如何进行质押呢?

NLP四范式:范式一:非神经网络时代的完全监督学习(特征工程);范式二:基于神经网络的完全监督学习(架构工程);范式三:预训练,精调范式(目标工程);范式四:预训练,提示,预测范式(Prompt工程)

Threejs Part 2: vertex concept, geometry structure

Mysql 将逗号隔开的属性字段数据由列转行
随机推荐
爱可可AI前沿推介(7.3)
Two sides of the evening: tell me about the bloom filter and cuckoo filter? Application scenario? I'm confused..
PHP production website active push (website)
Thread pool executes scheduled tasks
[combinatorics] non descending path problem (number of non descending paths with constraints)
Hands on in-depth learning notes (XIV) 3.7 Simple implementation of softmax regression
Characteristic polynomial and constant coefficient homogeneous linear recurrence
Arduino esp32: overall framework of lvgl project (I)
Nifi from introduction to practice (nanny level tutorial) - flow
2022.02.14_ Daily question leetcode five hundred and forty
A survey of state of the art on visual slam
arduino-esp32:LVGL项目(一)整体框架
远程办公之如何推进跨部门项目协作 | 社区征文
What material is sa537cl2? Analysis of mechanical properties of American standard container plate
斑马识别成狗,AI犯错的原因被斯坦福找到了
Shentong express expects an annual loss of nearly 1billion
Caching mechanism of Hibernate / session level caching mechanism
ThreeJS 第二篇:顶点概念、几何体结构
What material is 12cr1movr? Chemical property analysis of pressure vessel steel plate 12cr1movr
CC2530 common registers for timer 1