12個(gè) C# 11 新特性
所需成員
C# 11
required
為屬性和字段引入了一個(gè)新的修飾符,以強(qiáng)制構(gòu)造函數(shù)和調(diào)用者初始化這些值。如果初始化對(duì)象時(shí)缺少必需的成員,則會(huì)出現(xiàn)編譯錯(cuò)誤。
//?Initializations?with?required?properties?-?valid
var?p1?=?new?Person?{?Name?=?"Oleg",?Surname?=?"Kyrylchuk"?};
Person?p2?=?new("Oleg",?"Kyrylchuk");
//?Initializations?with?missing?required?properties?-?compilation?error
var?p3?=?new?Person?{?Name?=?"Oleg"?};
Person?p4?=?new();
public?class?Person
{
????public?Guid?Id?{?get;?set;?}?=?Guid.NewGuid();
????public?required?string?Name?{?get;?set;?}
????public?required?string?Surname?{?get;?set;?}
}
如果你有多個(gè)參數(shù)化構(gòu)造函數(shù),則應(yīng)
SetsRequiredMembers
在構(gòu)造函數(shù)上添加屬性,該屬性會(huì)初始化所有必需的成員。它通知編譯器正確的構(gòu)造函數(shù)。
public?class?Person
{
????public?Person()?{?}
????[SetsRequiredMembers]
????public?Person(string?name,?string?surname)
????{
????????Name?=?name;
????????Surname?=?surname;
????}
????public?Guid?Id?{?get;?set;?}?=?Guid.NewGuid();
????public?required?string?Name?{?get;?set;?}
????public?required?string?Surname?{?get;?set;?}
}
原始字符串文字
C# 11 引入了原始字符串文字。它允許包含任意文本而不轉(zhuǎn)義。
格式至少為三個(gè)雙引號(hào)
""".."""
。如果你的文本包含三個(gè)雙引號(hào),則應(yīng)使用四個(gè)雙引號(hào)將它們轉(zhuǎn)義。
結(jié)合字符串插值,計(jì)數(shù)
$
表示有多少個(gè)連續(xù)的大括號(hào)開始和結(jié)束插值。在下面的示例中,我想在 JSON 中使用插值,它已經(jīng)包含單個(gè)大括號(hào)
{}
。它會(huì)和字符串插值沖突,所以我用兩個(gè)
$$
來表示雙括號(hào)
{{}}
開始和結(jié)束插值。
string?name?=?"Oleg",?surname?=?"Kyrylchuk";
string?jsonString?=?
????$$"""
????{
????????"Name":?{{name}},
????????"Surname":?{{surname}}
????}
????""";
Console.WriteLine(jsonString);
UTF-8 字符串文字
C# 11 引入了 UTF-8 字符串文字。它只允許將 UTF-8 字符轉(zhuǎn)換為其字節(jié)表示。轉(zhuǎn)換在編譯時(shí)完成。
//?C#?10
byte[]?array?=?Encoding.UTF8.GetBytes("Hello?World");
//?C#?11
byte[]?array?=?"Hello?World";
列出模式
C# 11 引入了列表模式。
它擴(kuò)展了模式匹配以匹配數(shù)組或列表中的元素序列。你可以將列表模式與任何模式一起使用,包括常量、類型、屬性和關(guān)系模式。
var?numbers?=?new[]?{?1,?2,?3,?4?};
//?List?and?constant?patterns
Console.WriteLine(numbers?is?[1,?2,?3,?4]);?//?True
Console.WriteLine(numbers?is?[1,?2,?4]);????//?False
//?List?and?discard?patterns
Console.WriteLine(numbers?is?[_,?2,?_,?4]);?//?True
Console.WriteLine(numbers?is?[..,?3,?_]);???//?True
//?List?and?logical?patterns
Console.WriteLine(numbers?is?[_,?>=?2,?_,?_]);?//?True
字符串插值表達(dá)式中的換行符
C# 11 在字符串插值中引入了換行符。
它允許 { } 之間的任何有效 C# 代碼(包括換行符)來提高可讀性。
在插值中使用較長(zhǎng)的 C# 表達(dá)式時(shí),它很有幫助,例如模式匹配開關(guān)表達(dá)式或 LINQ 查詢。
//?switch?expression?in?string?interpolation
int?month?=?5;
string?season?=?$"The?season?is?{month?switch
{
????1?or?2?or?12?=>?"winter",
????>?2?and?<?6?=>?"spring",
????>?5?and?<?9?=>?"summer",
????>?8?and?<?12?=>?"autumn",
????_?=>?"unknown.?Wrong?month?number",
}}.";
Console.WriteLine(season);
//?The?season?is?spring.
//?LINQ?query?in?string?interpolation
int[]?numbers?=?new?int[]?{?1,?2,?3,?4,?5,?6?};
string?message?=?$"The?reversed?even?values?of?{nameof(numbers)}?are?{string.Join(",?",?numbers.Where(n?=>?n?%?2?==?0)
?????????????????????????????.Reverse())}.";
Console.WriteLine(message);
//?The?reversed?even?values?of?numbers?are?6,?4,?2.
自動(dòng)默認(rèn)結(jié)構(gòu)
C# 11 編譯器會(huì)自動(dòng)初始化未由結(jié)構(gòu)中的構(gòu)造函數(shù)初始化的任何字段或?qū)傩浴?/span>
下面的代碼在以前的 C# 版本中無法編譯。編譯器設(shè)置默認(rèn)值。
struct?Person
{
????public?Person(string?name)
????{
????????Name?=?name;
????}
????public?string?Name?{?get;?set;?}
????public?int?Age?{?get;?set;?}
}
Span<char>常量字符串的模式匹配
使用模式匹配,你可以測(cè)試字符串是否具有 C# 中的特定常量值。
C# 11 允許在常量字符串上匹配 a
Span<char>
和。
ReadOnlySpan<char>
ReadOnlySpan<char>?str?=?"Oleg".AsSpan();
if?(str?is?"Oleg")
{
????Console.WriteLine("Hey,?Oleg");
}
通用屬性
在 C# 中,如果要將類型傳遞給屬性,可以使用
typeof
表達(dá)式。
但是,沒有辦法限制允許傳遞的類型。C# 11 允許通用屬性。
class?MyType?{?}
class?GenericAttribute<T>?:?Attribute
????where?T:?MyType?
{
????private?T?_type;
}
[Generic<MyType>]
class?MyClass?{?}
擴(kuò)展nameof范圍
C# 11 擴(kuò)展了
nameof
表達(dá)式的范圍。
你可以在方法或參數(shù)聲明的屬性中指定方法參數(shù)的名稱。
此功能可用于添加屬性以進(jìn)行代碼分析。
public?class?MyAttr?:?Attribute
{
????private?readonly?string?_paramName;
????public?MyAttr(string?paramName)
????{
????????_paramName?=?paramName;
????}
}
public?class?MyClass
{
????[MyAttr(nameof(param))]
????public?void?Method(int?param,?[MyAttr(nameof(param))]?int?anotherParam)
????{?}
}
無符號(hào)右移運(yùn)算符
C# 11 引入了無符號(hào)右移運(yùn)算符
>>>
。
它向右移動(dòng)位,而不在每次移位時(shí)高位。
int?n?=?-32;
Console.WriteLine($"Before?shift:?bin?=?{Convert.ToString(n,?2),32},?dec?=?{n}");
int?a?=?n?>>?2;
Console.WriteLine($"After?????>>:?bin?=?{Convert.ToString(a,?2),32},?dec?=?{a}");
int?b?=?n?>>>?2;
Console.WriteLine($"After????>>>:?bin?=?{Convert.ToString(b,?2),32},?dec?=?{b}");
//?Output:
//?Before?shift:?bin?=?11111111111111111111111111100000,?dec?=?-32
//?After?????>>:?bin?=?11111111111111111111111111111000,?dec?=?-8
//?After????>>>:?bin?=???111111111111111111111111111000,?dec?=?1073741816
接口中的靜態(tài)抽象成員
C# 11 在接口中引入了靜態(tài)抽象成員。
你可以在接口中添加靜態(tài)抽象成員,以定義包含可重載運(yùn)算符、其他靜態(tài)成員和靜態(tài)屬性的接口。
public?interface?IAdditionOperator<TSelf,?TOther,?TResult>
????where?TSelf?:?IAdditionOperator<TSelf,?TOther,?TResult>
{
????static?abstract?TResult?operator?+(TSelf?left,?TOther?right);
}
通用數(shù)學(xué)
添加了靜態(tài)抽象成員功能以啟用通用數(shù)學(xué)支持。有關(guān)它的更多信息,你可以在此博客文章(https://devblogs.microsoft.com/dotnet/preview-features-in-net-6-generic-math/)中閱讀。
Point?p1?=?new()?{?X?=?10,?Y?=?5?};
Point?p2?=?new()?{?X?=?5,?Y?=?7?};
Point?p3?=?p1?+?p2;
Point?p4?=?p1?-?p2;
Console.WriteLine(p3);
Console.WriteLine(p4);
public?record?Point?:?
????IAdditionOperators<Point,?Point,?Point>,?
????ISubtractionOperators<Point,?Point,?Point>
{
????public?int?X?{?get;?set;?}
????public?int?Y?{?get;?set;?}
????public?static?Point?operator?+(Point?left,?Point?right)
????{
????????return?left?with?{?X?=?left.X?+?right.X,?Y?=?left.Y?+?right.Y?};
????}
????public?static?Point?operator?-(Point?left,?Point?right)?
????{
????????return?left?with?{?X?=?left.X?-?right.X,?Y?=?left.Y?-?right.Y?};
????}
????public?override?string?ToString()?=>?$"X:?{X};?Y:?{Y}";
轉(zhuǎn)自: 奧列格·基里爾丘克
鏈接:blog.okyrylchuk.dev/twelve-csharp-11-features
版權(quán)聲明:本文來源于網(wǎng)友收集或網(wǎng)友供稿,僅供學(xué)習(xí)交流之用,如果有侵權(quán),請(qǐng)轉(zhuǎn)告小編或者留言,本公眾號(hào)立即刪除。
支持小薇
騰訊云福利? :
騰訊云新春采購(gòu)節(jié),玩服務(wù)器的推薦使用(就這幾天時(shí)間):
2核2G4M 100%cpu性能??408元3年(3年活動(dòng),強(qiáng)烈推薦)
2核2G3M 100%cpu性能? ?30元/3月
https://url.cn/B87nTLu8
關(guān)注公眾號(hào)↑↑↑:DotNet開發(fā)跳槽?????
點(diǎn) 分 享

點(diǎn) 收 藏

點(diǎn) 點(diǎn) 贊
點(diǎn)在看
