What is the real purpose of get,set properties in

2019-05-07 20:07发布

问题:

Possible Duplicates:
Properties vs Methods
C#: Public Fields versus Automatic Properties

  • What is the real purpose of get,set properties in c#?
  • Any good ex when should i use get,set properties...

回答1:

you need them to have control over your object private fields values. for example if you don't wanna allow nulls or negative values for integers. Also, encapsulation is useful for triggering events on change of values of object members. Example

  bool started;
    public bool Started
    {
        get { return started; }
        set
        {
            started = value;
            if (started)
                OnStarted(EventArgs.Empty);
        }

    }

another example

    int positiveNumber;

    public int PositiveNumber
    {
        get { return positiveNumber; }
        set {
            if (value < 0)
                positiveNumber = 0;
            else positiveNumber = value;
        }
    }

and also another implementation of read only properties could be as follows

    int positiveNumber;

    public int PositiveNumber
    {
        get { return positiveNumber; }

    }


回答2:

Did you mean just properties or the keywords get; set;?

Properties: to put it easily, properties are smart fields. Smart being you can add logic when you want to get or set the value. Usage example: if you want to validate the values being set to a property or if you want to combine values from different fields without exposing those fields to the public.

The keywords: this is a C# shorthand to create a property with a backing field (the field that stores the values). It's useful when you're starting a new code and wanted to do the interface as early as possible.