为set方法中的属性赋值

Cem*_*mre 0 c# properties

下面的代码导致StackOverflow错误(正如预期的那样).但是,我希望能够在set方法中设置此变量的值.有没有办法做到这一点 ?

public bool IsAvailable 
{
    get
    {
        return IsAvailable;
    }

    set
    {
        if (value == true)
        {
            this.Shape.BrushColor = ColorAvailable;
            IsAvailable = true;
        }
        else
        {
            this.Shape.BrushColor = ColorNotAvailable;
            IsAvailable = false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*rth 8

您需要使用支持字段:

private bool _isAvailable;

public bool IsAvailable 
{
    get
    {
        return _isAvailable;
    }

    set
    {
        if (value == true)
        {
            this.Shape.BrushColor = ColorAvailable;
            _isAvailable = true;
        }
        else
        {
            this.Shape.BrushColor = ColorNotAvailable;
            _isAvailable = false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句:代码可以大大缩短:

private bool _isAvailable;

public bool IsAvailable 
{
    get
    {
        return _isAvailable;
    }

    set
    {
        this.Shape.BrushColor = value ? ColorAvailable : ColorNotAvailable;
        _isAvailable = value;
    }
}
Run Code Online (Sandbox Code Playgroud)