[英]Where can I find the documentation for "Nullable friendly pattern"?
In https://github.com/dotnet/csharplang/blob/master/proposals/csharp-9.0/nullable-reference-types-specification.md#element-access the following code is used, which I don't understand and I haven't found any documentation:在https://github.com/dotnet/csharplang/blob/master/proposals/csharp-9.0/nullable-reference-types-specification.md#element-access 中使用了以下代码,我不明白,我没有找到任何文档:
// Nullable friendly pattern
if (array[0] is { } o)
{
Console.WriteLine(o.ToString());
}
My incomprehension refers to the empty curly brackets.我的不理解是指空的大括号。 Where is documented how to understand / use this.
哪里记录了如何理解/使用它。 Is it possible to use this scheme "{ } var-name" in another place or is it bound to the usage with the is-operator?
是否可以在其他地方使用此方案“{} var-name”,还是绑定到 is-operator 的用法?
It is part of the C# pattern matching language feature, although not named explicitly as such.它是 C# 模式匹配语言功能的一部分,虽然没有明确命名。
The documentation about recursive pattern matching mentions it in the property pattern section, showing the ways to check for not null giving an example for a string
.关于递归模式匹配的文档在属性模式部分提到了它,展示了检查 not null 的方法,给出了一个
string
的例子。
Note that a null-checking pattern falls out of a trivial property pattern.
请注意,空检查模式不属于普通属性模式。 To check if the string s is non-null, you can write any of the following forms
要检查字符串 s 是否为非空,您可以编写以下任何形式
if (s is object o) ... // o is of type object
if (s is string x) ... // x is of type string
if (s is {} x) ... // x is of type string
if (s is {}) ...
A tutorial gives an other example where being used in a switch
statement and specifies 教程给出了另一个示例,其中在
switch
语句中使用并指定
The { } case matches any non-null object that didn't match an earlier arm.
{ } 案例匹配任何不匹配早期手臂的非空对象。
public decimal CalculateToll(object vehicle) => vehicle switch
{
Car c => 2.00m,
Taxi t => 3.50m,
Bus b => 5.00m,
DeliveryTruck t => 10.00m,
{ } => throw new ArgumentException(message: "Not a known vehicle type", paramName: nameof(vehicle)),
null => throw new ArgumentNullException(nameof(vehicle))
};
What happens is that if (array[0] is { } o)
gets translated into if (array[0] != null)
.发生的情况是
if (array[0] is { } o)
被转换为if (array[0] != null)
。
You can see it at https://sharplab.io你可以在https://sharplab.io看到它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.