C # 8.0 new features

C # 8.0 provides a number of enhancements

01 Readonly members
Can  readonly modifiers apply to any member of the structure. It indicates that the member does not modify the state. This ratio will  readonly modifiers used in  struct more sophisticated statement. Consider the following variable:
public struct Point
{
    public double X { get; set; }
    public double Y { get; set; }
    public double Distance => Math.Sqrt(X * X + Y * Y);

    public override string ToString() => $"({X}, {Y}) is {Distance} from the origin";
}

Like most of the same structure,  ToString() the method does not modify the state. It can be obtained by  readonly adding a modifier to  ToString() indicate this statement:

public readonly override string ToString() => $"({X}, {Y}) is {Distance} from the origin";

These changes will generate a compiler warning because the  ToString access  Distance attribute that is not marked as  readonly:

warning CS8656: Call to non-readonly member 'Point.Distance.get' from a 'readonly' member results in an implicit copy of 'this'

When you need to create a defensive copy of the compiler will issue a warning. Distance Property does not change the state, and therefore can be  readonly used to add a modifier to fix this warning statement:

public readonly double Distance => Math.Sqrt(X * X + Y * Y);

Please note that the readonly modifier for the read-only attribute is required. The compiler will not assume that  get access does not modify the state; must be explicitly stated  readonlyThe compiler will enforce the following rules: readonly members do not modify the state. Unless delete  readonly modifier, it would not compile the following methods:

public readonly void Translate(int xOffset, int yOffset)
{
    X += xOffset;
    Y += yOffset;
}

This feature allows you to specify design intent, the compiler can enforce the intent and optimized based on the intent.

02 members of the default interface

You can now add members to the interface, and provide implementations for these members. With this language feature, API author can add methods to a later version of the interface, without destroying the source or binary compatibility with this interface is currently implemented. Existing implementations inherit the default implementation. This function allows C # interoperating with the API for Android or Swift, such API supports similar functions. The default interface member also supports similar "feature" language feature program.

The default interface member will affect many programs and language elements. Refer to the default implementation update interface .

03 more models in use in more places
04 using statement
05 static local function
06 disposable ref structure
07 reference types can be empty
08 asynchronous stream
09 index and range

Guess you like

Origin www.cnblogs.com/SavionZhang/p/11201818.html