C# 8 位置模式与解构模式

C# 8 positional pattern vs. deconstruction pattern

在模式匹配的第一个提案中,递归模式是用以下语法定义的:

recursive_pattern
    : positional_pattern
    | property_pattern
    ;

Link: https://github.com/dotnet/csharplang/blob/master/proposals/patterns.md 为了演示位置模式,.Net 团队使用了 Cartesian exmaple,它覆盖了 is 运算符:

public static bool operator is(Cartesian c, out double R, out double Theta)

注意:我知道 'is' 运算符不能在 C# 中重写

在其他规范中: https://github.com/dotnet/csharplang/issues/1054

Recursive pattern matching defined like the following:
    pattern
        : declaration_pattern
        | constant_pattern
        | deconstruction_pattern
        | property_pattern
        ;

当我使用以下 Link 测试模式匹配(上述)时: https://sharplab.io

解构模式工作正常但位置模式不行(我不能覆盖位置模式建议示例中描述的 is opreator)

我的问题:

位置模式和解构模式有什么区别?

工作代码:

using System;

namespace ConsoleApp2
{
  class Program
  {
    static void Main(string[] args)
    {
      var stratec = new Company
      {
        Name = "stratec",
        Website = "wwww.stratec.com",
        HeadOfficeAddress = "Birkenfeld",
      };

      var firstEmploy = new Employ { Name = "Bassam Alugili", Age = 42, Company = stratec };

      var microsoft = new Company
      {
        Name = "microsoft",
        Website = "www.microsoft.com",
        HeadOfficeAddress = "Redmond, Washington",
      };

      var thidEmploy = new Employ { Name = "Satya Nadella", Age = 52, Company = microsoft };


      DumpEmploy(firstEmploy);
    }

    public static void DumpEmploy(Employ employ)
    {
      switch (employ)
      {

         case Employ{Name:"Bassam Alugili", Company:Company(_,_,_)} employTmp:
          {
            Console.WriteLine($"The employ:  {employTmp.Name}! 1");
          }
          break;


        default:
          Console.WriteLine("Unknow company!");
          break;
      }
    }
  }
}


public class Company
{
  public string Name { get; set; }

  public string Website { get; set; }

  public string HeadOfficeAddress { get; set; }

  public void Deconstruct(out string name, out string website, out string headOfficeAddress)
  {
    name = Name;
    website = Website;
    headOfficeAddress = HeadOfficeAddress;
  }
}

public class Employ
{
  public string Name { get; set; }

  public int Age { get; set; }

  public Company Company { get; set; }


  public void Deconstruct(out string name, out int age, out Company company)
  {
    name = Name;
    age = Age;
    company = Company;
  }
}

如何修改代码来测试位置模式!?

这是link:您也可以复制并粘贴代码,您将得到相同的结果:

Sharplab link with code

这是文件过期的问题and/or不清楚。 "positional" 和 "deconstruction" 是同义词,它们都指代括号内的子模式列表。

最新语法见https://github.com/dotnet/roslyn/blob/features/recursive-patterns/src/Compilers/CSharp/Portable/Syntax/Syntax.xml#L1816

递归模式有一个可选的类型、一个可选的解构模式子句(也称为位置模式子句)、一个可选的 属性 模式子句和一个可选的名称。

存在限制使用的语义规则(例如,您不能拥有一次省略所有可选部分的模式)。

解构模式子句是用括号括起来的子模式列表,这些子模式是带有可选名称冒号的模式。