为什么我的数组初始化代码会导致抛出 StackOverflowException?
我的类构造函数中的以下代码行抛出 StackOverflowException:
myList = new string[]{}; // myList is a property of type string[]
为什么会发生这种情况?初始化空数组的正确方法是什么?
更新:原因是在设置器中,我试图在其中修剪所有值:
set
{
for (int i = 0; i < myList.Length; i++)
{
if (myList[i] != null) myList[i] = myList[i].Trim();
}
}
The following line of code in my class constructor is throwing a StackOverflowException:
myList = new string[]{}; // myList is a property of type string[]
Why is that happening? And what's the proper way to initialize an empty array?
UPDATE: The cause was in the setter, in which I was attempting to trim all values:
set
{
for (int i = 0; i < myList.Length; i++)
{
if (myList[i] != null) myList[i] = myList[i].Trim();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果 myList 是一个属性,您是否检查了其 setter 的主体不会递归地分配给自身而不是支持字段,如下所示:
}
If myList is a property, did you check that the body of its setter does not recursively assign to itself instead of the backing field, as in:
}
这应该创建一个包含 0 个元素的数组。
编辑:我刚刚测试了
new string[] {}
并且它对我有用。也许你的 stackoverflow 的原因在其他地方。你能发布你的方法的其余部分吗?一般来说,堆栈溢出特别是在执行大量递归方法调用时发生。像这样:
This should create an array with 0 elements.
EDIT: I just tested
new string[] {}
and it works for me. Maybe the reason for your stackoverflow is elsewhere.Can you post the rest of your method? Generally spoken, stackoverflows occur specially when performing a high number recursive method calls. Like this:
您的
set
代码实际上并未分配任何内容,而是引用其自身。我有一种感觉,你误解了属性的运作方式。您需要一个由属性操作的支持变量:然后您需要让您的
set
代码与该变量一起工作:如果您尝试访问
myList
,它正在访问自身,这就是然后访问自身等,导致无限递归和堆栈溢出。Your
set
code doesn't actually assign anything, and refers to itself. I have a feeling you're misunderstanding how properties work. You need a backing variable which the property manipulates:And then you need to have your
set
code work with that variable:If you try and access
myList
, it's accessing itself, which then accesses itself, etc, leading to infinite recursion and a stack overflow.看来 @Jonas H 所说的是准确的,您可能会递归地修改属性而不是其支持字段。
错误
正确
It appears as though what @Jonas H said is accurate, you may be recursivly modifying the Property instead of its backing field.
WRONG
RIGHT