C#中的花括号 [英] Curly Braces In C#
问题描述
我在玩一些代码,我想知道是否有人可以告诉我这段代码中的大括号代表什么.我以为这是一个空对象,但似乎并非如此.
I was playing around with some code and I was wondering if any can tell me what the curly braces in this code represents. I thought it would've been for an empty object but that doesn't seem to be the case.
Person person = new Person{};
if (person is {}){
Console.WriteLine("Person is empty.");
} else {
Console.WriteLine("Person is not empty.");
}
它编译得很好;但是如果我填充 person 类的属性,它仍然属于 if 语句的 person is empty 部分.
It compiles just fine; but if I populate the properties of the person class it still falls into the person is empty part of the if statement.
推荐答案
{} 在此上下文中表示任何类型的模式匹配以检查实例是否不为空:
{} means in this context a pattern matching of any type to check if the instance is not null:
if(person != null){ //the same as: if(person is {})...
}
它就像一个用于模式匹配的 var 关键字,因此您不需要显式指定/重复类型(尽管您知道).
It is like a var keyword for pattern matching, so you do not need to specify/repeat the type explicitly (although you know it).
if(GetPersonFromDb() is {} person){ //the same as: var person = GetPersonFromDb(); if(person != null)...
}
更多信息(请参阅特殊匹配表达式部分):https://hackernoon.com/whats-pattern-matching-in-c-80-6l7h3ygm
More info (see the section Special match expressions): https://hackernoon.com/whats-pattern-matching-in-c-80-6l7h3ygm
这篇关于C#中的花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!