What is the real purpose of get,set properties in

2019-05-07 19:16发布

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...

2条回答
姐就是有狂的资本
2楼-- · 2019-05-07 19:53

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; }

    }
查看更多
smile是对你的礼貌
3楼-- · 2019-05-07 20:04

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.

查看更多
登录 后发表回答