0

下面的代码会导致 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;
        }
    }
}
4

6 回答 6

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

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

private bool _isAvailable;

public bool IsAvailable 
{
    get
    {
        return _isAvailable;
    }

    set
    {
        this.Shape.BrushColor = value ? ColorAvailable : ColorNotAvailable;
        _isAvailable = value;
    }
}
于 2013-05-13T12:30:04.710 回答
1

您的属性应该封装一个私有字段,并且应该在 Setter 中设置,而不是在属性中。

private bool _IsAvailable; //private field
public bool IsAvailable 
{
    get
    {
        return _IsAvailable;
    }

    set
    {
        if (value)
        {
            this.Shape.BrushColor = ColorAvailable;
        }
        else
        {
            this.Shape.BrushColor = ColorNotAvailable;
        }
        _IsAvailable = value;
    }
}
于 2013-05-13T12:30:12.127 回答
1

您可以使用支持字段:

private bool _IsAvailable;
public bool IsAvailable 
{
    get
    {
        return _IsAvailable;
    }

    set
    {
        this.Shape.BrushColor = value ? ColorAvailable : ColorNotAvailable;
        _IsAvailable = value;
    }
}

自动与显式属性

于 2013-05-13T12:31:19.380 回答
1

您可以创建一个私人成员private bool _isAvailable并将您的标志存储在那里。

public bool IsAvailable 
{
get
{
    return _isAvailable;
}

set
{
    if (value)
    {
        this.Shape.BrushColor = ColorAvailable;
    }
    else
    {
        this.Shape.BrushColor = ColorNotAvailable;
    }
    _isAvailable = value;
}

}

于 2013-05-13T12:31:20.833 回答
1

您应该使用支持字段。但是,如果您不想使用支持字段并确保this.Shape.BrushColor不会在其他任何地方设置它,您可以执行以下操作(丑陋),例如:

public bool IsAvailable 
{
    get
    {
        return this.Shape.BrushColor == ColorAvailable;
    }
    set
    {
        this.Shape.BrushColor = value  ? ColorAvailable : ColorNotAvailable;               
    }
}
于 2013-05-13T12:33:20.710 回答
0

本质上 IsAvailable 是属性,而不是@Cemre 正确地说的基础(支持)字段,例如;

private bool _isAvailable;

我还会考虑减少冗长,例如,'(value == true)' 与 'if (value)' 相同,并在 if...else 之外设置基础字段的值,并且仅在一条线。这样,上述内容可以简化为;

set
{
    this.Shape.BrushColor = value?ColorAvailable:ColorNotAvailable;
    _isAvailable = false;
}
于 2013-05-13T12:39:48.440 回答