c#中getter/setter中的无限循环
本文关键字:无限循环 setter getter | 更新日期: 2023-09-27 18:14:55
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的"进程已终止"消息。知道我哪里做错了吗?
编辑:今天我知道我做了一件非常愚蠢的事。考虑到大量的即时反应。现在我明白了。您有一个无限递归,因为您在属性中引用属性。
你应该使用一个后备字段:
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; }
}
...
在属性的getter中有一个循环引用。试试这个:
class Something
{
private int _testCount;
public int TestCount
{
get { return _testCount; }
set { _testCount = value; }
}
public void DoIt(int val)
{
_testCount = val;
}
}
This:
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;
}
}