26 Şubat 2018 Pazartesi

C# 7.0 Pattern Matching

Giriş
Bu özellik C# 7.0 ile geliyor. C# 7.1 ile de genişletiliyor. Açıklaması şöyle
Pattern matching in C# 7.0 has a requirement stating that there must be an explicit or implicit conversion from the left-hand-side type to the right-hand-side type.

In C# 7.1, the spec will be expanded so that either the left-hand-side or the right-hand-side can be an open type.
3 farklı çeşidi var.
1.Constant pattern
2.Type pattern - case içinde bir değişken tanımlanır
3.Var pattern - If içinde bir değişken tanımlanır

Visitor Örüntüsü
Pattern Matching yerine Visitor örüntüsü de kullanılabilir. Ancak Pattern Matching çok daha kolay :)

Type Pattern
Örnek
Şöyle yaparız. Çıktı olarak defaut alırız.
string str = null; 
switch(str){
  case string x:
    Console.WriteLine("string " + x);
    break;
  default:
    Console.WriteLine("default");
    break;
}
Var Pattern
Söz dizimi şöyle.
expr is var varname
Açıklaması şöyle.
Var patterns of the form var x (where x is an identifier), which always match, and simply put the value of the input into a fresh variable x with the same type as the input.
Örnek
Şöyle yaparız.
string someString = null;
switch (someString)
{
  case string s:
    Console.WriteLine("string s");
    break;
  case var o:
    Console.WriteLine("var o");
    break;
}
Örnek
Şöyle yaparız.
object[] items = { new Book("The Tempest"), new Person("John") };
foreach (var item in items) {
  if (item is var obj)
    Console.WriteLine($"Type: {obj.GetType().Name}, Value: {obj}"); 
}

Hiç yorum yok:

Yorum Gönder