模式匹配

C#的模式匹配擴充套件實現了函式式語言模式匹配的許多好處,但是以一種與底層語言的感覺平滑整合的方式

switch 表達

模式匹配擴充套件了 switch 語句以切換型別:

class Geometry {} 

class Triangle : Geometry
{
    public int Width { get; set; }
    public int Height { get; set; }
    public int Base { get; set; }
}

class Rectangle : Geometry
{
    public int Width { get; set; }
    public int Height { get; set; }
}

class Square : Geometry
{
    public int Width { get; set; }
}

public static void PatternMatching()
{
    Geometry g = new Square { Width = 5 }; 
    
    switch (g)
    {
        case Triangle t:
            Console.WriteLine($"{t.Width} {t.Height} {t.Base}");
            break;
        case Rectangle sq when sq.Width == sq.Height:
            Console.WriteLine($"Square rectangle: {sq.Width} {sq.Height}");
            break;
        case Rectangle r:
            Console.WriteLine($"{r.Width} {r.Height}");
            break;
        case Square s:
            Console.WriteLine($"{s.Width}");
            break;
        default:
            Console.WriteLine("<other>");
            break;
    }
}

is 表達

模式匹配擴充套件了 is 運算子以檢查型別並同時宣告一個新變數。

Version < 7
string s = o as string;
if(s != null)
{
    // do something with s
}

可以改寫為:

Version >= 7
if(o is string s)
{
    //Do something with s
};

另請注意,模式變數 s 的範圍擴充套件到 if 塊之外,到達封閉範圍的末尾,例如:

if(someCondition)
{
   if(o is string s)
   {
      //Do something with s
   }
   else
   {
     // s is unassigned here, but accessible 
   }

   // s is unassigned here, but accessible 
}
// s is not accessible here