2 Temmuz 2020 Perşembe

Local Function

Giriş
Bu özellik C# 7 ile geliyor. _() {...} şeklinde metod içinde bir başka metod tanımlanır. Açıklaması şöyle
Many designs for classes include methods that are called from only one location. These additional private methods keep each method small and focused.
Local functions enable you to declare methods inside the context of another method. Local functions make it easier for readers of the class to see that the local method is only called from the context in which it is declared.
Örnek
Şöyle yaparız. Local function return kelimesinden sonra tanımlanıyor.
public static int Foo()
{
  return _();

  // declare the body of _()
  int _()
  {
    return 5;
  }
}
Çağırmak için şöyle yaparız
void Main()
{
  Console.WriteLine(Foo()); // Prints 5
}
Örnek
Şöyle yaparız. Local function kullanıldığı yerden önce tanımlanıyor.
private void btnEdit_Click(object sender, EventArgs e)
{
  if (guestList.SelectedRows.Count > 0)
  {
    String foo(int cell)
    {
       return ...;
    }
        
    int.Parse(foo(2)), ...);
    ...
  }
  else
  {
    ...
  }
}
Örnek
Capturing yapılabilir. Şöyle yaparız.
public int MultiplyFoo(int id)
{
  return LocalBar(id);

  int LocalBar(int number)
  {
    return number * 2;
  }
}
Şu kod ile aynıdır.
public int MultiplyFoo(int id)
{
  return LocalBar();

  int LocalBar()
  {
    return id * 2;
  }
}

Hiç yorum yok:

Yorum Gönder