C# { }运算符

3

我无法在任何地方找到这个,你能告诉我在 C# 中表达式{ }的含义或给我一个文档链接吗?

以下是我在我的项目中发现的使用示例:

Method(IProfileDocument profileDocument)
{
    if(profileDocument.documentId is not { } documentId
    || string.IsNullOrEmpty(documentId))
    { 
       do something...
    }
}

也许这会有所帮助:https://learn.microsoft.com/zh-cn/dotnet/csharp/language-reference/language-specification/basic-concepts#77-scopes - Ibrennan208
花括号是表示作用域的一种方式,它展示了另一个成员所封装的内容。 - Ibrennan208
您也可能在字符串插值中看到它们的使用。 - Ibrennan208
你也可能在数组或列表声明中看到它们:new int[] { 1, 2, 3 }; - Ibrennan208
否则您可能正在询问此问题的副本:https://dev59.com/ylIG5IYBdhLWcg3w8Wmu - Ibrennan208
这个回答解决了你的问题吗?“is”运算符后面花括号的含义 - mkrieger1
2个回答

5

1
这个参考文献中包含了问题中看到的 (s is {} x) 模式及其等效语句。不可否认,它是该语言中最奇怪的结构之一。 - NPras
那么 (s is {} x) 和 (s is not {} x) 有什么区别呢? - Ellbar
不是否定模式,isis not之间的区别应该是不言自明的 :-) - Piglet

1

属性模式:属性模式检查输入值不为null,并通过可访问的属性或字段递归匹配提取的值。

                string s =null;
                if (s is not { } documentId)
                {

                }
                else
                {
                    string mj = documentId;
                }

声明模式:声明模式既测试一个表达式是否属于给定类型,如果测试成功,则将其转换为该类型。如果指定为单一变量设计,则可能会引入一个名为指定标识符的给定类型本地变量。

此处首先检查 profileDocument.documentId 是否为空。如果不为空,则将值分配给一个新的变量 documentId

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/patterns#property-pattern


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接