简体   繁体   中英

In C#, how do you mix a default get with an explicit set?

I want to do something like this:

class Foo
{
    bool Property
    {
        get;
        set
        {
            notifySomethingOfTheChange();
            // What should I put here to set the value?
        }
    }
}

Is there anything I can put there to set the value? Or will I have to explicitly define the get and add another field to the class?

There is no way.

  • You can either have both setter and getter auto-implemented

     bool Property { get; set; } 
  • Or implement both manually

     bool Property { get { return _prop; } set { _prop = value; } } 

You either have a default property, with compiler-generated backing field and getter and/or setter body, or a custom property.

Once you define your own setter, there is no compiler-generated backing field. You have to make one yourself, and define the getter body also.

No this is the case where auto-properties are not the best fit, and therefore the point at which you go to proper implemented properties:

class Foo
{
    private bool property;
    public bool Property
    {
        get
        {
            return this.property;
        }
        set
        {
            notifySomethingOfTheChange();
            this.property = value
        }
    }
}

In many cases you can use the "Auto Property" feature eg public int Age { get; set; } = 43;

This is a good reference http://www.informit.com/articles/article.aspx?p=2416187

Naji K.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM