更改Property的值后的StackOverFlow-Exception

时间:2014-06-27 15:54:59

标签: c# stack-overflow

当我想要更改属性的值时,我得到一个StackOverFlow-Exception" CurrentState":

CurrentState = State.quequed;

enter image description here

1 个答案:

答案 0 :(得分:2)

这是一个简单的逻辑错误和无限递归的问题"因为CurrentState属性正在尝试设置自己。解决方案很简单。

目前你有这个(简化)

public State CurrentState {
    set {
        // ...

        CurrentState = state.Whatever;

        // ...
    }
    get {
        return ???; /// ??? => I don't know what you're returning?
    }
}

解决方案:创建一个支持字段,以便该属性不会自行调用。

private State _currentState;

public State CurrentState {
    set {
        // ...

        // This is for illustration purposes. Normally you'd be checking 
        // or assigning the value of the "value" parameter, not always 
        // setting the same value as this suggests.
        _currentState = state.Whatever;

        // ...
    }
    get {
        return _currentState;
    }
}