我在玩一些代码,我想知道是否有人可以告诉我这段代码中的花括号代表什么。我以为这是一个空对象,但似乎并非如此。
Person person = new Person{};
if (person is {}){
Console.WriteLine("Person is empty.");
} else {
Console.WriteLine("Person is not empty.");
}
Run Code Online (Sandbox Code Playgroud)
它编译得很好;但是如果我填充了 person 类的属性,它仍然属于 if 语句的 person is empty 部分。
Rob*_*t J 10
{} 在此上下文中表示任何类型的模式匹配,以检查实例是否不为 null:
if(person != null){ //the same as: if(person is {})...
}
Run Code Online (Sandbox Code Playgroud)
它就像用于模式匹配的 var 关键字,因此您不需要显式指定/重复类型(尽管您知道)。
if(GetPersonFromDb() is {} person){ //the same as: var person = GetPersonFromDb(); if(person != null)...
}
Run Code Online (Sandbox Code Playgroud)
更多信息(请参阅特殊匹配表达式部分):https://hackernoon.com/whats-pattern-matching-in-c-80-6l7h3ygm