博客 / 詳情

返回

從 .NET Core1.0 到 .NET 10:.NET + C# 演進全景

本文回顧微軟 .NET 與 C# 語言從跨平台起步到統一平台、再到現代化性能優化的全過程。每個版本都配有簡明 Demo 代碼,便於開發者快速掌握特性變化與實踐。

一、.NET Core 時代:跨平台的開端

1. .NET Core 1.x(C# 7.0)
  • 發佈時間:.NET Core 1.0 於 2016-06-27 發佈。

  • 意義:標誌 .NET 生態邁向真正跨平台、開源。

  • C# 7.0 核心特性

    • Out 變量內聯聲明

    • 元組 (tuple) 返回多個值

    • 模式匹配 (pattern matching)

  • Demo 代碼

if (int.TryParse("123", out int number)) // Out 變量內聯
{
    Console.WriteLine(number);
}

(string name, int age) GetPerson() => ("Alice", 30); // 元組
var person = GetPerson();
Console.WriteLine($"Name: {person.name}, Age: {person.age}");

object obj = "Hello";
if (obj is string str) // 模式匹配
{
    Console.WriteLine(str.Length);
}
2. .NET Core 2.x(C# 7.1~7.3)
  • 發佈時間:.NET Core 2.0 於 2017-08-14 發佈。

  • 意義:性能大幅提升,支持 .NET Standard 2.0,庫生態更加豐富。

  • C# 7.1~7.3 核心特性

    • async Main 方法

    • 默認表達式 (default literal)

    • 元組投影初始值設定項(tuple element name inference)

  • Demo 代碼

public static async Task Main(string[] args) // async Main
{
    await Task.Delay(100);
    Console.WriteLine("Async Main done");
}

int number = default; // 默認表達式
var tuple = (name: "Alice", age: 30); // 元組投影初始值
Console.WriteLine($"Name: {tuple.name}, Age: {tuple.age}");
3. .NET Core 3.x(C# 8.0)
  • 發佈時間:.NET Core 3.0 於 2019-09-23 發佈。

  • 意義:首次將 Windows 桌面(WPF/WinForms)納入 .NET Core 支持,並引入高性能結構如 Span。

  • C# 8.0 核心特性

    • 可空引用類型 (nullable reference types)

    • 異步流 (async IAsyncEnumerable)

    • 模式和索引 (indices & ranges)

    • using 聲明簡化 (using var)

  • Demo 代碼

string? nullableString = null; // 可空引用類型

async IAsyncEnumerable<int> GetAsyncNumbers()
{
    for (int i = 0; i < 5; i++)
    {
        await Task.Delay(50);
        yield return i;
    }
}

await foreach (var n in GetAsyncNumbers())
{
    Console.WriteLine(n);
}

using var reader = new StreamReader("file.txt"); // using 聲明
int[] arr = {1, 2, 3, 4};
int last = arr[^1]; // 索引操作
Console.WriteLine(last);

二、統一平台時代:.NET 5 到 .NET 10

4. .NET 5(C# 9.0)
  • 發佈時間:.NET 5 於 2020-11-10 發佈。

  • 意義:標誌 “.NET Framework” + “.NET Core” 向統一 .NET 平台合併。

  • C# 9.0 核心特性

    • 記錄類型 (record)

    • 頂級語句 (top-level statements)

    • 模式匹配增強(關係模式、邏輯模式)

  • Demo 代碼

public record Person(string FirstName, string LastName); // 記錄類型

// 頂級語句
Console.WriteLine("Hello, World from C# 9!");

// 模式匹配增強
Person person = new("Alice", "Smith");
if (person is { LastName: "Smith" })
{
    Console.WriteLine("Found Smith");
}
5. .NET 6(C# 10.0)
  • 發佈時間:.NET 6 於 2021-11-08 發佈。

  • 意義:LTS(長期支持)版,推進統一平台願景,性能與開發體驗進一步優化。

  • C# 10.0 核心特性

    • 全局 using 指令 (global using)

    • 文件範圍的命名空間 (file-scoped namespace)

    • 記錄結構 (record struct)

    • 常量插值字符串 (constant interpolated strings)

  • Demo 代碼

// GlobalUsings.cs
global using System;
global using System.Collections.Generic;

// Program.cs
namespace MyApp; // 文件範圍命名空間

public readonly record struct Point(int X, int Y); // 記錄結構

const string name = "World";
const string greeting = $"Hello, {name}!"; // 常量插值字符串

Console.WriteLine(greeting);
6. .NET 7(C# 11.0)
  • 發佈時間:.NET 7 於 2022-11-08 發佈。

  • 意義:專注於性能提升、雲原生支持、AOT(前向編譯)改進。

  • C# 11.0 核心特性

    • 原始字符串字面量 (raw string literals)

    • 列表模式 (list patterns)

    • 必需成員 (required members)

    • 泛型數學 (generic math)

  • Demo 代碼

string xml = """
<person>
    <name>Alice</name>
    <age>30</age>
</person>
"""; // 原始字符串字面量

public class Person
{
    public required string FirstName { get; set; }
    public required string LastName { get; set; }
}

// 泛型數學 簡化示例
static T Add<T>(T x, T y) where T : System.Numerics.INumber<T>
    => x + y;

Console.WriteLine(Add<int>(3, 4));
7. .NET 8(C# 12.0)
  • 發佈時間:.NET 8,於 2023-11 發佈(實際 2023-11-14)

  • 意義:LTS 版,原生 AOT 正式版、進一步性能優化。

  • C# 12.0 核心特性

    • 主構造函數 (primary constructors) 支持所有 class/struct。(Microsoft Learn)

    • 集合表達式 (collection expressions) 和擴展初始化語法。
      -(還包括別名任意類型(using alias any type)、inline 數組等)

  • Demo 代碼

// 主構造函數示例
public class Person(string name, int age) // C# 12 主構造函數
{
    public string Name => name;
    public int Age => age;
}

// 集合表達式示例
int[] array = [1, 2, 3];
List<int> list = [1, 2, 3];

// 使用 spread 運算符 ..(假設已支持)
int[] other = [4, 5];
int[] combined = [1, 2, ..other, 6];
8. .NET 9(C# 13.0)
  • 發佈時間:.NET 9 於 2024-11-12 發佈。

  • 意義:繼續推進性能優化、智能化開發(AI 集成等)

  • C# 13.0 核心特性(你原文提及)包括:

    • params 集合增強(支持任意集合類型而不僅是數組)

    • field 關鍵字 簡化屬性訪問器中字段引用

    • ref struct 實現接口

    • 部分屬性和索引器增強

  • 説明:經校驗發現,關於這些具體特性的官方資料仍較少、屬於預覽或提案階段。建議在博客中註明 “預覽/提案” 狀態。

  • Demo 代碼(按你原文)

public void ProcessItems(params ReadOnlySpan<int> items) // params 集合增強
{
    foreach (var item in items)
    {
        Console.WriteLine(item);
    }
}

public class Example
{
    private int _backing;
    public string Name
    {
        get;
        set => field = value ?? throw new ArgumentNullException(nameof(value)); // field 關鍵字
    }
}
9. .NET 10(C# 14.0)
  • 發佈時間:.NET 10 目前為最新里程碑版本。

  • 意義:進一步提升開發者生產力、性能表現。

  • C# 14.0 核心特性

    • 擴展成員 (extension members):新增擴展屬性、靜態擴展成員、用户定義運算符等。(Microsoft Learn)

    • 空條件賦值 (null-conditional assignment):可以在左側使用 ?. 進行賦值。

    • nameof 支持未綁定泛型

    • Lambda 參數修飾符簡化

  • Demo 代碼

// 擴展成員示例(C# 14)
public static class EnumerableExtensions
{
    extension<TSource>(IEnumerable<TSource> source)  // 擴展塊
    {
        // 擴展屬性
        public bool IsEmpty => !source.Any();

        // 擴展方法
        public IEnumerable<TSource> WhereEven(Func<TSource, bool> predicate)
            => source.Where(predicate);
    }

    extension<TSource>(IEnumerable<TSource>)  // 靜態擴展成員
    {
        public static IEnumerable<TSource> Combine(IEnumerable<TSource> first, IEnumerable<TSource> second)
            => first.Concat(second);

        public static IEnumerable<TSource> Identity => Enumerable.Empty<TSource>();

        public static IEnumerable<TSource> operator + (IEnumerable<TSource> left, IEnumerable<TSource> right)
            => left.Concat(right);
    }
}

// 空條件賦值示例
Person? person = null;
person?.Name = "Alice"; // 只有當 person 不為 null 時才賦值

// nameof 支持未綁定泛型
string typeName = nameof(List<>); // "List"

// Lambda 參數修飾簡化(示例)
delegate bool TryParse<T>(string s, out T value);
TryParse<int> parse = (s, out value) => int.TryParse(s, out value);

三、核心演進趨勢總結

通過從 .NET Core 1.0 到 .NET 10、從 C# 7.0 到 C# 14 的演進,幾個核心趨勢十分明顯:

  1. 跨平台與統一化:從 Windows 專屬的 .NET Framework,到真正跨平台的 .NET Core,再到統一平台 .NET。

  2. 性能持續優化:運行時、垃圾回收 (GC)、JIT/AOT、結構 (Span) 等不斷強化。

  3. 開發體驗簡化:語言特性持續減少樣板代碼(boilerplate),如頂級語句、全局 using、主構造函數、擴展成員等。

  4. 現代化/雲原生:容器支持、微服務、AOT、雲端運行優化。

  5. 智能化與擴展能力:後期語言版本引入擴展成員、泛型數學、AI 集成等,提升 “智能應用” 構建能力。

四、版本選擇建議

  • 新項目:推薦使用最新的 LTS 版本(如 .NET 10)以獲得最新特性與性能撥優。

  • 現有項目遷移:建議先升級到最近的 LTS(如 .NET 6、.NET 8),然後再考慮遷移至 .NET 10。遷移前需考慮:第三方庫支持、語言特性兼容性、開發工具版本(Visual Studio/VS Code)、API 棄用情況等。

  • 謹慎預覽特性:對於尚在預覽或提案階段的語言特性(如 C# 13 的某些特性),應慎重使用於生產環境,並註明“預覽中”。

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.