gpt4 book ai didi

c# - C#中的花括号

转载 作者:行者123 更新时间:2023-12-03 17:01:27 26 4
gpt4 key购买 nike

我在玩一些代码,我想知道是否有人可以告诉我这段代码中的花括号代表什么。我以为这是一个空对象,但似乎并非如此。

 Person person = new Person{};

if (person is {}){
Console.WriteLine("Person is empty.");
} else {
Console.WriteLine("Person is not empty.");
}

它编译得很好;但是如果我填充了 person 类的属性,它仍然属于 if 语句的 person is empty 部分。

最佳答案

{} 在此上下文中表示任何类型的模式匹配,以检查实例是否为空:

if(person != null){     //the same as: if(person is {})...

}
它就像用于模式匹配的 var 关键字,因此您不需要显式指定/重复类型(尽管您知道)。
if(GetPersonFromDb() is {} person){     //the same as: var person = GetPersonFromDb(); if(person != null)...

}
更多信息(参见特殊匹配表达式部分): https://hackernoon.com/whats-pattern-matching-in-c-80-6l7h3ygm

关于c# - C#中的花括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60103804/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com