2 Nisan 2018 Pazartesi

readonly Anahtar Kelimesi

Giriş
Açıklaması şöyle.
When a field-declaration includes a readonly modifier, the fields introduced by the declaration are readonly fields. Direct assignments to readonly fields can only occur as part of that declaration or in an instance constructor or static constructor in the same class.
static ve readonly
Tercih edilen sıra şöyle.
[access modifiers] [static] [readonly] [volatile]
Şöyle yaparız, ancak static readonly yerine const kullanmak belki daha iyi olabilir.
private static readonly string s_profileFilename = "";
readonly Alan Sadece Referansın Değişmemesi Demek
readonly nesne aslında bir yalan. Nesnenin için değiştirilebilir. Elimizde şöyle bir liste olsun
private readonly List<Foo> _items = new List<Foo>();
Açıklaması şöyle.
Marking a field as readonly has no impact on allocations etc. It also doesn't make the list read-only: just the field. You can still Add() / Remove() / Clear() etc. The only thing you can't do is change the list instance to be a completely different list instance; you can, of course, still completely change the contents. And read-only is a lie anyway: reflection and unsafe code can modify the value of a readonly field.
readonly Alan ve Static Constructor
readonly alan, static constructor içinde değiştirilebilir. Şöyle yaparız.
public class Class1
{
  private const int ConstantInt = 42;
  private static readonly int StaticInt = 42;

  static Class1()
  {
    StaticInt = -20;
  }

  
}

Hiç yorum yok:

Yorum Gönder