DotNETWeekly-io/DotNetWeekly

【文章推荐】C# 11 中检查集合空

Closed this issue · 1 comments

image

C# 11 中包含了模式匹配功能可以帮助写出更加优雅的代码,尤其是集合的 Null 或者空判断。

var collection = new Collection<object>();

if (collection is null or [])
{
    Console.WriteLine("collection is not null or empty");
}

var array = (string[])null;

if (array is null or [])
{
    Console.WriteLine("array is null or empty");
}

array = Array.Empty<string>();

if (array is null or [])
{
    Console.WriteLine("array is null or empty");
}