getter / setter中的无限循环c#

class Program { static void Main(string[] args) { something s = new something(); s.DoIt(10); Console.Write(s.testCount); } } class something { public int testCount { get { return testCount; } set { testCount = value + 13; } } public void DoIt(int val) { testCount = val; } } 

是我拥有的,因为我想测试和玩C#的getter / setter东西。 但是,我得到一个StackOverFlowException未处理“set {testCount = value + 13}”。 我无法单步执行它,因为我得到一个“调试器无法继续运行进程。进程被终止”来自Visual Studio的消息。 我有什么想法我做错了吗?

编辑:今天我了解到我做了一个非常愚蠢的derp。 鉴于大量的即时反应。 现在我知道的更好。

您有无限递归,因为您指的是属性的属性。

您应该使用支持字段:

 private int testCount; public int TestCount { get { return testCount; } set { testCount = value + 13; } } 

注意属性名称TestCount (也符合C#命名标准),而不是字段名称testCount (小写t )。

您应该声明一个变量来支持该属性:

 class something { private int _testCount; public int testCount { get { return _testCount; } set { _testCount = value + 13; } } ... 

您在房产的吸气器中有一个循环参考。 试试这个:

 class Something { private int _testCount; public int TestCount { get { return _testCount; } set { _testCount = value; } } public void DoIt(int val) { _testCount = val; } } 

这个:

 public int testCount { get { return testCount; } 

它返回自身,导致它自己执行。

而不是返回自己的属性本身,将目标值存储在另一个(最好是受保护的或私有的)变量中。 然后在setter和getter中操作该变量。

 class Program { static void Main(string[] args) { something s = new something(); s.DoIt(10); Console.Write(s.testCount); } } class something { private int _testCount; public int testCount { // you are calling the property within the property which would be why you have a stack overflow. get { return _testCount; } set { _testCount = value + 13; } } public void DoIt(int val) { testCount = val; } }