【问题标题】:Where can I find the documentation for "Nullable friendly pattern"?我在哪里可以找到“可空友好模式”的文档?
【发布时间】:2020-11-22 23:27:30
【问题描述】:

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());
}

我的不理解是指空大括号。哪里记录了如何理解/使用它。 是否可以在其他地方使用此方案“{ } var-name”,还是与 is-operator 的用法绑定?

【问题讨论】:

  • “我在哪里可以找到文档”是一个不好的问题。 “什么是可为空的友好模式以及如何使用它”会是一个更好的问题。
  • @Guy Incognito:我正在寻找两者,但首先是文档。
  • @Julian 人们总是把“我不明白这个问题”和“这个问题不清楚”混为一谈。

标签: c#


【解决方案1】:

它是 C# 模式匹配语言功能的一部分,尽管没有明确命名。

关于recursive pattern matching 的文档在属性模式部分提到了它,展示了检查不为空的方法,并给出了string 的示例。

请注意,空值检查模式不属于琐碎的属性 图案。要检查字符串 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 {}) ...

tutorial 给出了另一个在switch 语句中使用并指定的示例

{ } 情况匹配任何不匹配早期分支的非空对象。

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))
};

发生的情况是if (array[0] is { } o) 被翻译成if (array[0] != null)。
你可以在https://sharplab.io看到它

【讨论】:

  • 那么将if (s is string x)解释为“如果s有一个类型(即s不为空)并且该类型是string”是否正确?
  • @KevinKrumwiede 没错,因为if (s is string x) s 将是一个不为空的string。
  • 非常感谢您的回答以及其他所有人的支持。
猜你喜欢
  • 1970-01-01
  • 2012-12-20
  • 2011-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-08
  • 1970-01-01
  • 2010-09-13
相关资源
最近更新 更多