古詩詞大全網 - 個性簽名 - 馬克。中的20個新API。網絡6

馬克。中的20個新API。網絡6

NET 6引入了兩種期待已久的類型——date only和TimeOnly,它們分別代表DateTime的日期和時間部分。

DateOnly DateOnly = new(2021,9,25);

控制臺。WriteLine(date only);

TimeOnly timeOnly = new ( 19,0,0);

控制臺。WriteLine(time only);

date only dateOnlyFromDate = date only。FromDateTime(日期時間。現在);

控制臺。WriteLine(dateOnlyFromDate);

time only time onlyfromdate = time only。FromDateTime(日期時間。現在);

控制臺。WriteLine(time onlyfromdate);

它可以控制多個異步任務的並行性。

var userHandlers = new []

{

"用戶/okyrylchuk ",

"用戶/jaredpar ",

"用戶/大衛·福爾"

};

使用HttpClient client = new()

{

BaseAddress =新Uri(" "),

};

客戶。DefaultRequestHeaders。用戶代理。add(new ProductInfoHeaderValue(" dot net "," 6 "));

ParallelOptions選項= new()

{

MaxDegreeOfParallelism = 3

};

等待並行。foreach sync(user handlers,options,async ( uri,token)= & gt;

{

var user = await客戶端。GetFromJsonAsync & ltGitHubUser & gt(uri,token);

控制臺。WriteLine ( $ "Name: {user。姓名}簡歷:{用戶。bio }”;

});

公共類GitHubUser

{

公共字符串名稱{ get設置;}

公共字符串Bio { get設置;}

}

//輸出:

//姓名:大衛·福勒

//簡歷:微軟ASP.NET團隊的合作軟件架構師,SignalR的創建者

//

//姓名:奧列格·基裏丘克

// Bio:軟件開發者| Dotnet | C# | Azure

//

//姓名:賈裏德·帕森斯

//Bio:Developer on c#編譯器

ArgumentNullException的壹個小改進,在拋出異常之前不需要在每個方法中都檢查null,現在只需要寫壹行,和response。AssureSuccessstatusCode();類似。

example method(null);

void示例方法(對象參數)

{

ArgumentNullException。ThrowIfNull(param);

//做點什麽

}

添加的數據結構。NET 6的PriorityQueue有壹個關聯的優先級,決定了出隊順序,編號小的元素先出隊。

優先級隊列& ltstring,int & gtpriority queue = new();

優先級隊列。入隊("秒",2);

優先級隊列。入隊(“第四”,4);

優先級隊列。Enqueue("第三個1 ",3);

優先級隊列。入隊(“第三個2”,3);

優先級隊列。入隊("第壹",1);

while ( priorityQueue。Count & gt0 )

{

string item = priorityQueue。dequeue();

控制臺。WriteLine(項目);

}

//輸出:

//首先

//秒

//第三個2

//第三個1

//第四

提供基於偏移量的API,用於以線程安全的方式讀寫文件。

使用SafeFileHandle handle = File。OpenHandle ( "file.txt ",access : FileAccess。讀寫);

//寫入文件

byte [] strBytes =編碼。UTF8。GetBytes(" Hello world ");

ReadOnlyMemory buffer 1 = new(strBytes);

等待隨機訪問。WriteAsync ( handle,buffer1,0);

//獲取文件長度

長長度= RandomAccess。GetLength(句柄);

//從文件中讀取

Memory buffer2 = new(新字節[長度]);

等待隨機訪問。ReadAsync ( handle,buffer2,0);

字符串內容=編碼。UTF8。GetString ( buffer2。ToArray());

控制臺。WriteLine(內容);//妳好世界

知道壹個完全異步的“PeriodicTimer”,比較適合用在異步場景。它有壹個WaitForNextTickAsync方法。

//壹個構造函數:public periodic timer(TimeSpan period)

使用periodic timer timer = new(TimeSpan。from秒(1));

while(等待計時器。WaitForNextTickAsync())

{

控制臺。WriteLine(日期時間。utc now);

}

//輸出:

//13-Oct-21 19:58:05PM

//13-Oct-21 19:58:06PM

//13-Oct-21 19:58:07PM

//13-Oct-21 19:58:08PM

//13-Oct-21 19:58:09PM

//13-Oct-21 19:58:10PM

//13-Oct-21 19:58:11PM

//13-Oct-21 19:58:12PM

// ...

。NET 6實現了開放度量API規範,並內置了指示器API。以下指示器是通過Meter類創建的。

?計數器

?柱狀圖

?可觀察計數器

?可觀測儀表

使用的方法如下:

var builder =應用程序。CreateBuilder(參數);

var app = builder。build();

//創建儀表

var meter = new Meter ( "MetricsApp "," v 1.0 ");

//創建計數器

計數器計數器=米。create counter(" Requests ");

app。使用((context,next)= & gt;

{

//記錄測量值

櫃臺。加(1);

返回下壹個(上下文);

});

app。MapGet ( "/",()= & gt《Hello World》);

startmetelistener();

app。run();

//創建並啟動儀表監聽器

void StartMeterListener()

{

var listener = new meter listener();

聽眾。instrument published =(instrument,meter listener)= & gt;

{

如果(儀器。Name == "請求" & amp& amp儀器。米。Name == "MetricsApp ")

{

//開始收聽特定的測量記錄

meterListenerEnableMeasurementEvents(儀器,空);

}

};

聽眾。SetMeasurementEventCallback((儀器,測量,標簽,狀態)= & gt

{

控制臺。WriteLine($ " Instrument { Instrument。Name}已記錄測量值:{ measurement }”;

});

聽眾。start();

}

它提供反射成員的可空性信息和上下文:

?參數信息參數

?FieldInfo字段

?PropertyInfo屬性

?EventInfo事件

var示例= new Example();

var nullability info context = new nullability info context();

foreach(示例中的var propertyInfo。GetType()。GetProperties())

{

var nullability info = nullability info context。create(property info);

控制臺。WriteLine ( $ "{propertyInfo。Name}屬性為{ nullabilityInfo。WriteState }”);

}

//輸出:

// Name屬性可為空

//屬性值不為空

班級示例

{

公共字符串?Name { get設置;}

公共字符串值{ get設置;}

}

它允許您獲取嵌套元素的可空信息。您可以指定數組屬性必須為非空,但元素可以為空,反之亦然。

type Example type = type of(Example);

property info notNullableArrayPI = example type。GetProperty ( nameof(示例。NotNullableArray));

property info nullableArrayPI = example type。GetProperty ( nameof(示例。nullable array));

nullabilityinfocext nullabilityinfocext = new();

NullabilityInfo notNullableArrayNI = nullabilityinfocext。create(notNullableArrayPI);

控制臺。WriteLine ( notNullableArrayNI。ReadState);// NotNull

控制臺。WriteLine ( notNullableArrayNI。ElementType。ReadState);//可空

NullabilityInfo nullableArrayNI = nullabilityinfocext。create(nullableArrayPI);

控制臺。WriteLine ( nullableArrayNI。ReadState);//可空

控制臺。WriteLine ( nullableArrayNI。ElementType。ReadState);//可空

班級示例

{

公共字符串?[]NotNullableArray { get;設置;}

公共字符串?[]?NullableArray { get設置;}

}

直接通過環境獲取進程ID和路徑。

int processId =環境。ProcessId

字符串路徑=環境。ProcessPath

控制臺。WriteLine(processId);

控制臺。WriteLine(路徑);

它與DI的GetRequiredService()相同,如果缺少它,就會拋出異常。

web application builder builder = web application。CreateBuilder(參數);

WebApplication app = builder。build();

my settings my settings = new();

//如果缺少所需的配置部分,將引發InvalidOperationException

app。配置。GetRequiredSection ( "MySettings ")。bind(my settings);

app。run();

分類我的設置

{

公共字符串?設置值{ get設置;}

}

您可以輕松地從加密安全的偽隨機數生成器(CSPNG)中生成隨機值序列。

它在下列情況下很有用:

?密鑰生成

?隨機數字

?壹些簽名方案

//用加密的強隨機值序列填充300字節的數組。

//GetBytes(byte[]data);

// GetBytes(byte[]數據,int偏移量,int計數)

// GetBytes(int count)

// GetBytes(跨度數據)

byte[]bytes = RandomNumberGenerator。GetBytes(300);

NET 6引入了新的API來分配NativeMemory,Native Memory有分配和釋放內存的方法。

危險的

{

byte * buffer =(byte *)native memory。alloc(100);

自然記憶。免費(緩沖);

/*該類包含主要用於管理本機內存的方法。

公共靜態類本機內存

{

public unsafe static void * aligned alloc(nuint byteCount,nuint alignment);

public unsafe靜態void aligned free(void * ptr);

公共不安全靜態void * AlignedRealloc ( void * ptr,nuint byteCount,nuint alignment);

公共不安全靜態void * Alloc(nuint byteCount);

public unsafe static void * Alloc(numint element count,numint elementSize);

公共不安全靜態void * AllocZeroed(nuint byteCount);

public unsafe static void * AllocZeroed(nuint element count,nuint elementSize);

public unsafe static void Free(void * ptr);

公共不安全靜態void * Realloc ( void * ptr,nuint byteCount);

}*/

}

NET 6引入了壹種處理2的冪的新方法。

?“IsPow2”確定指定的值是否是2的冪。

?“RoundUpToPowerOf2”將指定值舍入到2的冪。

// IsPow2計算指定的Int32值是否是2的冪。

控制臺。WriteLine ( BitOperations。ispow 2(128));//真

//rounduppowerof 2對指定的T:System進行舍入。UInt32值最大為2的冪。

控制臺。WriteLine ( BitOperations。rounduppowerof 2(200));// 256

您可以等待異步任務更容易地執行,如果它超時,將拋出“TimeoutException”。

task operation task = DoSomethingLongAsync();

等待operationTask。WaitAsync ( TimeSpan。from seconds(5));

異步任務DoSomethingLongAsync()

{

控制臺。WriteLine(" DoSomethingLongAsync已啟動。");

等待任務。延遲(時間跨度。from秒(10));

控制臺。WriteLine(" DoSomethingLongAsync已結束。");

}

//輸出:

// DoSomethingLongAsync已啟動。

//未處理的異常。操作已超時。

新方法:

?辛科斯

?往復直線

?往復檢驗

新重載:

?最小值、最大值、Abs、符號、夾鉗支架nint和nuint。

?DivRem返回壹個元組,包括商和余數。

//新方法SinCos、ReciprocalEstimate和ReciprocalSqrtEstimate

//同時計算Sin和Cos

(雙sin,雙cos ) =數學。辛科斯(1.57);

控制臺。WriteLine($ " Sin = { Sin } Cos = { Cos } ");

//計算1 / x的近似值

double recEst = Math。往復運動(5);

控制臺。WriteLine ( $ "倒數估計= { recEst } ");

//計算1 / Sqrt(x)的近似值

double recSqrtEst = Math。reciprocalsqrtestimeta(5);

控制臺。WriteLine ( $ "倒數sqrt估計值= { recSqrtEst } ");

//新重載

// Min、Max、Abs、Clamp和Sign支持nint和nuint

(nint a,nint b ) = ( 5,10);

nint min =數學。Min ( a,b);

nint max =數學。Max ( a,b);

nint abs =數學。ABS(a);

nint clamp =數學。夾鉗(絕對、最小、最大);

nint符號=數學。標誌(a);

控制臺。WriteLine($ " Min = { Min } Max = { Max } Abs = { Abs } ");

控制臺。WriteLine($ " Clamp = { Clamp } Sign = { Sign } ");

// DivRem變量返回壹個元組

(int商,int余數)= Math。DivRem ( 2,7);

控制臺。WriteLine ( $ "商= {商}余數= {余數} ");

//輸出:

// Sin = 0.9999996829318346

//Cos = 0.0007963267107331026

//倒數估計= 0.2

//倒數sqrt估計值= 0.4472135954999579

// Min = 5

// Max = 10

// Abs = 5

// Clamp = 5

// Sign = 1

//商= 0

//余數= 2

這是在循環或修改字典中的結變量結構時使用的,可以減少結構的重復,避免字典中的重復哈希計算。這個有點晦澀。有興趣的可以看看這個。

/dotnet/runtime/issues/27062

字典& ltint,MyStruct & gtdictionary = new()

{

{ 1,新的MyStruct { Count = 100 } }

};

int key = 1;

ref my struct value = ref collection marshal。GetValueRefOrNullRef(字典,鍵);

//返回Unsafe。如果不存在,則為NullRef();檢查使用不安全。IsNullRef(引用值)

如果(!不安全。IsNullRef(引用值))

{

控制臺。WriteLine(值。計數);//輸出:100

//就地變異

價值。count++;

控制臺。WriteLine(值。計數);//輸出:101

}

結構MyStruct

{

public int Count { get設置;}

}

IHostBuilder上新的ConfigureHostOptions API使得配置應用程序變得更加容易。

公開課程

{

公共靜態void Main ( string [] args)

{

CreateHostBuilder(參數)。構建()。run();

}

公共靜態IHostBuilder CreateHostBuilder(string[]args)= & gt;

主持人。CreateDefaultBuilder(參數)

。ConfigureHostOptions(o = & gt;

{

哦。ShutdownTimeout = TimeSpan。from minutes(10);

});

}

NET 6引入了壹個新的CreateAsyncScope方法。在處理IAsyncDisposable的服務時,現有的CreateScope方法會拋出異常,使用CreateAsyncScope可以完美解決這個問題。

使用var provider = new service collection()等待

。AddScoped & lt示例& gt()

。BuildServiceProvider();

等待使用(var scope = provider。CreateAsyncScope())

{

var示例=範圍。服務提供商。GetRequiredService & lt示例& gt();

}

類示例:IAsyncDisposable

{

public value task dispose async()= & gt;違約;

}

?解密

?解密Cfb

?解密b

?EncryptCbc

?EncryptCfb

?EncryptEcb

靜態字節[]解密(字節[]密鑰,字節[] iv,字節[]密文)

{

使用(Aes aes = Aes。Create())

{

aes。Key = key

返回aes。DecryptCbc(密文,iv,PaddingMode。pkcs 7);

}

}