當前位置: 妍妍網 > 碼農

C# 12 中的新功能介紹(帶範例)

2024-04-19碼農


概述: 隨著 C# 12 的即將釋出,以下是新功能的編譯列表,以及如何使用它們的實際範例。Lambda 運算式中的預設參數這是一個簡單的更改。這在之前使用 DefaultParameterValue 是可能的,但新的實作要簡潔得多。var myMethod = (int a, int b = 1) = a + b; var myVar = myMethod(5); // this returns 6別名 帶有「using」別名指令的任何型別透過使用「using」alias 指令,您現在可以為幾乎任何型別添加別名,包括可為 null 的值型別。不支持可為 null 的參照型別。使用別名可以透過刪除不必

隨著 C# 12 的即將釋出,以下是新功能的編譯列表,以及如何使用它們的實際範例。

Lambda 運算式中的預設參數

這是一個簡單的更改。這在之前使用 DefaultParameterValue 是可能的,但新的實作要簡潔得多。

var myMethod = (int a, int b = 1) => a + b;
var myVar = myMethod(5); // this returns 6

別名 帶有「using」別名指令的任何型別

透過使用「using」alias 指令,您現在可以為幾乎任何型別添加別名,包括可為 null 的值型別。不支持可為 null 的參照型別。使用別名可以透過刪除不必要的冗長程式碼來提高可讀性。

usingOptionalFloat = float?;
usingUser = (string name,int id);
// Aliased types can be used anywhere, including as function parameters
publicvoidPrintUser(User user) => Console.WriteLine(user.name);

主要建構函式

C# 12 最初是在 C# 9 中針對記錄型別引入的,現在將此功能擴充套件到所有類和結構。這樣做的目的是允許我們向類別宣告中添加參數,以便在您的類中使用,以簡潔起見。

public classPost(string title, int upvotes, int downVotes)
{
publicstring Title => string.IsNullOrWhiteSpace(title) ? "" : title.Trim();
publicint Score => upVotes - downVotes;
}

行內陣列

行內陣列使開發人員能夠為結構型別建立固定大小的陣列。這些將主要由執行時團隊和庫建立者用作提高效能的一種方式。正如 Microsoft 的文件中所述,您可能不會顯式建立它們,但會透明地使用它們。如果您好奇,此功能的草稿中有冗長的解釋。

[System.Runtime.CompilerServices.InlineArray(10)]
publicstructMyInlineArray
{
privateint _item;
}
var myArray = newMyInlineArray();
for (int i = 0; i < 10; i++)
{
myArray[i] = i;
}
foreach (var i in myArray)
{
Console.WriteLine(i);
}

集合運算式

集合運算式為您提供了建立公共集合的新語法。現在,您還可以使用行內的擴充套件運算子「..」來傳播一個集合與另一個集合的值。請參閱以下範例:

int[] a = [1, 2];
int[] b = [3, 4];
int[] c = [..a, ..b];
foreach (var i in c)
{
Console.WriteLine(i);
}
// produces 1, 2, 3, 4

攔截 器

對於高級程式設計師來說,攔截器是一個有趣的新功能,目前被標記為實驗性功能,可能不會進入最終版本。_偵聽器_是一種可以在編譯時用自身替換_可攔截_方法的方法。若要啟用此功能,由於它仍處於實驗階段,因此必須將以下行添加到計畫檔中:

<Features>InterceptorsPreview</Features>

現在我們已經啟用了該功能,讓我們在Program.cs中試用一下:

usingSystem;
usingSystem.Runtime.CompilerServices;
var my class = newMy class();
my class.SayHello(); // this prints "Hello from the interceptor!"
public classMy class
{
publicvoidSayHello()
{
Console.WriteLine("Hello from My class");
}
}
publicstatic classInterceptor class
{
[InterceptsLocation("Program.cs", line: 8, character: 17)]
publicstaticvoidInterceptorMethod(thisMy class my class)
{
Console.WriteLine("Hello from the interceptor!");
}
}

我們這裏有一個名為 My class 的基本類,它有一個名為 SayHello 的方法,它只打印字串「Hello from My class」。然後下面我們有 Interceptor class,其中有 InterceptorMethod。請註意它上面的「InterceptsLocation」內容 — 這是您希望此方法截獲另一個方法的檔、行和字元的位置。在本例中,我們已將檔Program.cs以及 SayHello 方法所在的行和字元放在一起,並告訴編譯器將該方法替換為此新方法。

如果你喜歡我的文章,請給我一個贊!謝謝