三个运算符导致StackOverflowException

时间:2016-03-22 14:58:16

标签: c# exception operator-keyword

我知道,在这种情况下我可以简单地使用abs,但我只是好奇:为什么会发生这种情况?

public float maxThrotle{
    set { maxThrotle = value < 0 ? -value : value;    //this line causes problem
    }
    get { return maxThrotle; }
}

1 个答案:

答案 0 :(得分:2)

通过尝试从属性设置器中调用属性设置器,导致无限循环。

您可能希望创建一个私有支持字段来存储值,如下所示:

private float maxThrotle;
public float MaxThrotle {
    set { maxThrotle = value < 0 ? -value : value;    //this line causes problem
    }
    get { return maxThrotle; }
}

注意我根据大多数C#编码标准重命名该属性以使用大写字母。

(另外,单词 throttle 拼写为双-t - )。

相关问题