C#各版本新功能 C#8.0


ReadOnly 成員

默認接口方法

接口里面的方法都是虛方法,字類不用寫override 就能對其進行覆蓋;

這與抽象類里面的方法是不同的,接口管理的更加隨意;以后都可以用面向接口開發了;

若是同時繼承了接口1跟接口2,接口1,2都實現了方法 TurnOnFor

    public interface Interface1
    {
        public void TurnOnFor(int duration)
        {
            Task.Delay(duration);
            Console.WriteLine("我是接口 Interface1 里面的原始方法");
        }
    }

    public interface Interface2: Interface1
    {
        public void TurnOnFor(int duration)
        {
        }
    }

   public class Child : Interface2
    {
    }

    Interface1 child = new Child();

    child.TurnOnFor(11); //調用接口1中的方法

    Interface2 child = new Child();

    child.TurnOnFor(11); //調用接口2中的方法

模式匹配增強

Using 聲明 升級

  using() //以前
{}

//現在

using var file =***

//方法的最后會自動幫你釋放

靜態本地函數

添加 static 修飾符,以確保本地函數不會從封閉范圍捕獲(引用)任何變量

int M () {     int y = 5 ;     int x = 7 ;     return Add(x, y);

static int Add ( int left, int right ) => left + right; }

可處置的ref結構

可為空的引用類型

異步流

索引和范圍

var words = new string[]
{
                // index from start    index from end
    "The",      // 0                   ^9
    "quick",    // 1                   ^8
    "brown",    // 2                   ^7
    "fox",      // 3                   ^6
    "jumped",   // 4                   ^5
    "over",     // 5                   ^4
    "the",      // 6                   ^3
    "lazy",     // 7                   ^2
    "dog"       // 8                   ^1
};              // 9 (or words.Length) ^0

var quickBrownFox = words[1..4];
var lazyDog = words[^2..^0];
var allWords = words[..]; // contains "The" through "dog".
var firstPhrase = words[..4]; // contains "The" through "fox"
var lastPhrase = words[6..]; // contains "the", "lazy" and "dog"

Null合並賦值

C# 8.0 引入了 null 合並賦值運算符 ??= 。 ok

僅當左操作數計算為 null 時,才能使用運算符 ??= 將其右操作數的值分配給左操作數 ok

非托管構造類型

嵌套表達式中的StackAlloc

內插逐字字符串的增強功能 ok

解釋說明: $ 和 @,這兩個符號誰在前面都可以了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM