2 Eylül 2018 Pazar

Auto Property

Auto Property
Property kelimesi C# dilinde başka bir anlam kazanmış, biraz scripting dillerindeki Property ile karıştırılmaya müsait bir kelime. Normalde Java ve C#'ta sınıf alanlarına "Field" denilir. C++'ta ise "member variable" denilir.

Bir Field'ın compiler tarafından yaratılması, get ve set metodlarının otomatik oluşturulmasını istiyorsak Auto Property kullanırız.

Auto Property ile Serialization
Property'ler serialize edilirler.

Auto Property ile Modifier
Getter ve Setter modifier alabiliyor. Şöyle yaparız:
public string foo { get; private set; }
AutoProperty ve Kalıtım
Ata sınıfta Auto Property virtual modifier kelimesi ile tanımlanır. Şöyle yaparız.
public class MyBase {
  public virtual String A {
    get {
      return "getBaseA";
    }
    set {
      throw new NotSupportedException("setBaseA");
    }
  }
}
Alt sınıfta Auto Property override modifier kelimesi ile tanımlanır. Şöyle yaparız.
public class MyDerivedA: MyBase {
  public override String A {
    get {
      return "s";
    }
    set { // set is overridden, now set does nothing
    }
  }
}
Get ve Set metodlarından istediğimizi override ederiz. Eğer Set'i override etmek istemiyorsak şöyle yaparız.
public class MyDerivedB: MyBase {
  public override String A {
    get {
      return "s";
    }
    // set is not overridden, same as in the base class
  }
}
Bu durumda şu davranışı elde ederiz.
// Does nothing: overridden MyDerivedA.A.set is called
MyBase test1 = new MyDerivedA();
test1.A = "Sample";

// Will throw NotSupportedException (base MyBase.A.set is called)
MyBase test2 = new MyDerivedB();
test2.A = "Sample";
Auto Property Initializer
Açıklaması şöyle.
C# 6 enables you to assign an initial value for the storage used by an auto-property in the auto-property declaration:
Şöyle yaparız.
public class CustomerResult
{
  public string CompanyStatus { get; set; }
  public OverallResult Result { get; set; } = new OverallResult();
}
Auto Property Initializer For Read Only Fields
Auto Property Initializer For Read Only Fields yazısına taşıdım

Ne Zaman Public Metod Tercih Edilmeli
Bir property her bir zaman değer dönmelidir. Hesaplanan değerlerin property yerine public metod yapılması tavsiye ediliyor.

Auto Property ile Inline Kod
Property'ler inline edilebilirler ancak ben böyle iyileştirmeleri ömrüm boyunca sevmedim.
private SqlMetaData[] meta;

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private SqlMetaData[] Meta
{
  get
  {
    return this.meta;
  }
}
Auto Property Ref Parametre Olarak Kullanılamaz
MSDN şöyle diyor
You can't use the ref and out keywords for the following kinds of methods:
  • Async methods, which you define by using the async modifier.
  • Iterator methods, which include a yield return or yield break statement.
  • Properties are not variables. They are methods, and cannot be passed to ref parameters.






Hiç yorum yok:

Yorum Gönder