为set方法中的属性赋值

时间:2013-05-13 12:28:57

标签: 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;
        }
    }
}

6 个答案:

答案 0 :(得分: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;
        }
    }
}

BTW:代码可以大大缩短:

private bool _isAvailable;

public bool IsAvailable 
{
    get
    {
        return _isAvailable;
    }

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

答案 1 :(得分: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;
    }
}

答案 2 :(得分:1)

您可以使用支持字段:

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

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

Automatic vs Explicit Properties

答案 3 :(得分:1)

您可以创建私人会员private bool _isAvailable并将您的国旗存储在那里。

public bool IsAvailable 
{
get
{
    return _isAvailable;
}

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

}

答案 4 :(得分:1)

您应该使用支持字段。但是如果你不想使用支持字段,并确保this.Shape.BrushColor不会在其他任何地方设置,你可以做一些事情(丑陋),如:

public bool IsAvailable 
{
    get
    {
        return this.Shape.BrushColor == ColorAvailable;
    }
    set
    {
        this.Shape.BrushColor = value  ? ColorAvailable : ColorNotAvailable;               
    }
}

答案 5 :(得分:0)

基本上IsAvailable属性不是像@Cemre正确说的那样,是一个基础的(支持)字段,如;

private bool _isAvailable;

我还会考虑减少详细程度,例如,'(value == true)'与'if(value)'相同,并设置if ... else之外的基础字段的值并且只在一条线上。通过这种方式,上述内容可以简化为;

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