C# 冷知识(二)

34 阅读1分钟

模式匹配

以往都是使用 == 或者 != 判断是否相等

object? obj = null;
if (obj != null)
{
    Console.WriteLine("obj is not null");
}

使用模式匹配可以达到同样效果,它会使用最正确的方式判断两者是否相等

object? obj = null;
if (!(obj is null))
{
    Console.WriteLine("obj is not null");
}

if (obj is not null)
{
    Console.WriteLine("obj is not null");
}

此外,还有 or 、 and 、not、忽略匹配等用法

int a = 3;
if (a == 2 || a == 3 || a == 5 || a == 7 || a == 11)
{
    Console.WriteLine("a is a prime number");
}

if (a is 2 or 3 or 5 or 7 or 11)
{
    Console.WriteLine("a is a prime number");
}

if (a is >2 and < 5)
{
    Console.WriteLine("a is a prime number");
}

var pair = (3, 5);
if(pair is ( > 2, < 6))
{
    Console.WriteLine("pass");
}

// 忽略匹配
if (pair is ( > 2,_))
{
    Console.WriteLine("pass");
}

if (pair is ( > 2, not 4))
{
    Console.WriteLine("pass");
}

对数组复杂判断

var arr = new[] { 1, 3, 5, 7 };
if(arr is [1,not 2, < 6, >= 6])
{
    Console.WriteLine("pass");
}

Debugger 调试

当调试时需要查看某个对象属性时,默认需要点开对象查看属性

image.png

我们可以通过重写ToString方法打印指定的内容

image.png

还可以使用[DebuggerDisplay("xxxx")]查看属性,并且无需写$符

image.png

若调试时不想查看某个属性,可以使用[DebuggerBrowsable(DebuggerBrowsableState.Never)]

image.png

若调试时想跳过某个步骤,可在执行方法上添加[DebuggerHidden]

image.png

null > 0

一般调用列表时,会对其是否为空进行判断

List<int>? list= null;
if(list!=null&& list.Count() > 0)
{

}

可以使用 list?.Count() > 0 简化书写流程

List<int>? list= null;
if(list?.Count() > 0)
{

}