C# 更改属性值后出现StackOverFlow异常

C# 更改属性值后出现StackOverFlow异常,c#,stack-overflow,C#,Stack Overflow,当我想更改属性“CurrentState”的值时,会出现StackOverFlow异常: 这是一个简单的逻辑错误和“无限递归”问题,因为CurrentState属性正试图自行设置。解决办法很简单 目前你有这个(简化) 解决方案:创建一个支持字段,使属性不会调用自身 private State _currentState; public State CurrentState { set { // ... // This is for illustrati

当我想更改属性“CurrentState”的值时,会出现StackOverFlow异常:


这是一个简单的逻辑错误和“无限递归”问题,因为
CurrentState
属性正试图自行设置。解决办法很简单

目前你有这个(简化)

解决方案:创建一个支持字段,使属性不会调用自身

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

发布您的代码,而不是图像,它显示您正在访问属性,而不是备份字段。这就是它递归调用
get
的原因。您的代码只是递归调用自身。您需要为属性使用一个备份字段。看,这肯定与你的问题有关,如果不是重复的话。不,这不是重复的。我想我删除了以前存在的字段,但我忘记了,所以我不知道为什么会发生这种情况。
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;
    }
}