Programing

읽기 전용 및 가져 오기 전용 속성을 사용해야하는 경우

lottogame 2020. 8. 30. 19:39
반응형

읽기 전용 및 가져 오기 전용 속성을 사용해야하는 경우


.NET 응용 프로그램에서 "ReadOnly"속성을 사용해야하는 경우와 "Get"만 사용해야하는 경우 이 둘의 차이점은 무엇입니까?

private readonly double Fuel= 0;

public double FuelConsumption
{
    get
    {
        return Fuel;
    }
}        

또는

private double Fuel= 0;

public double FuelConsumption
{
     get
     {
          return Fuel;
     }
}

getter 만 사용하여 속성을 만들면 클래스 외부에있는 코드에 대해 속성이 읽기 전용이됩니다.

그러나 클래스에서 제공하는 메소드를 사용하여 값을 변경할 수 있습니다.

public class FuelConsumption {
    private double fuel;
    public double Fuel
    {
        get { return this.fuel; }
    }
    public void FillFuelTank(double amount)
    {
        this.fuel += amount;
    }
}

public static void Main()
{
    FuelConsumption f = new FuelConsumption();

    double a;
    a = f.Fuel; // Will work
    f.Fuel = a; // Does not compile

    f.FillFuelTank(10); // Value is changed from the method's code
}

클래스의 private 필드 readonly를로 설정하면 필드 값을 한 번만 설정할 수 있습니다 (인라인 할당 또는 클래스 생성자 사용). 나중에 변경할 수 없습니다.

public class ReadOnlyFields {
    private readonly double a = 2.0;
    private readonly double b;

    public ReadOnlyFields()
    {
        this.b = 4.0;
    }
}

readonly 클래스 필드는 클래스 생성 중에 초기화되는 변수에 자주 사용되며 나중에 변경되지 않습니다.

In short, if you need to ensure your property value will never be changed from the outside, but you need to be able to change it from inside your class code, use a "Get-only" property.

If you need to store a value which will never change once its initial value has been set, use a readonly field.


As of C# 6 you can declare and initialise a 'read-only auto-property' in one line:

double FuelConsumption { get; } = 2;

You can set the value from the constructor but not other methods.


A property that has only a getter is said to be readonly. Cause no setter is provided, to change the value of the property (from outside).

C# has has a keyword readonly, that can be used on fields (not properties). A field that is marked as "readonly", can only be set once during the construction of an object (in the constructor).

private string _name = "Foo"; // field for property Name;
private bool _enabled = false; // field for property Enabled;

public string Name{ // This is a readonly property.
  get {
    return _name;  
  }
}

public bool Enabled{ // This is a read- and writeable property.
  get{
    return _enabled;
  }
  set{
    _enabled = value;
  }
} 

readonly properties are used to create a fail-safe code. i really like the Encapsulation posts series of Mark Seemann about properties and backing fields:

http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx

taken from Mark's example:

public class Fragrance : IFragrance
{
    private readonly string name;

    public Fragrance(string name)
    {
        if (name == null)
        {
            throw new ArgumentNullException("name");
        }

        this.name = name;
    }

    public string Spread()
    {
        return this.name;
    }
}

in this example you use the readonly name field to make sure the class invariant is always valid. in this case the class composer wanted to make sure the name field is set only once (immutable) and is always present.


Methods suggest something has to happen to return the value, properties suggest that the value is already there. This is a rule of thumb, sometimes you might want a property that does a little work (i.e. Count), but generally it's a useful way to decide.

참고URL : https://stackoverflow.com/questions/2719699/when-should-use-readonly-and-get-only-properties

반응형