question on get; set;
I would like to set a modified flag when ever I change one of the class properties as shown below
public bool Modified { get; set; }
public bool Enabled { get; set { Modified = true; } }
proble开发者_如何转开发m is I have an error and the compiler is asking me to declare a body for the get; I would rather not have to declare a separate private variable, is there another way to do this.
c#, ,net-2
thanks
No. If you want an explicit setter, you can't use an automatic getter. So you must have something like:
private bool _Enabled;
public bool Modified { get; set; }
public bool Enabled
{
    get 
    {
        return _Enabled;
    }
    set 
    {
        _Enabled = value; 
        Modified = true;
    }
}
This is not possible. C# does not allow you to specify a body for one or the other of get or set but have the other implemented automatically. If you need to do this, you need a manual property with a backing field.
Note that you want something like this:
public bool Modified { get; set; }
private bool enabled;
public bool Enabled {
    get { return this.enabled; }
    set {
        if(this.enabled != value) {
            this.enabled = value;
            this.Modified = true;
        }
    }
}
I think you need to write the getter and setter for Enabled in full:
public bool Modified { get; set; }
private bool enabled;
public bool Enabled
{
    get { return enabled; }
    set
    {
        if (enabled != value)
        {
            Modified = true;
            enabled = value;
        }
    }
}
since a automatic generated member will be created for get; set; property then you cant declare one of them otherwise you have to set them by your own
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论