为什么设置一个静态方法导致堆栈溢出?堆栈、静态、方法

2023-09-04 05:31:04 作者:紫荆私语

为什么我得到一个堆栈溢出错误,如果我用set访问改变类的静态成员在C#?

Why do I get a stack overflow error if I use the set accessor to change a static class member in C#?

我不争论这是一个错误,我只是想知道究竟是什么在机器的内部事情。

I am not disputing this as a bug, I just want to know what exactly is going on in the internals of the machine.

推荐答案

您不应该;我希望你有这样的:

You shouldn't; I expect you have something like:

private static int foo;
public static int Foo {
    get {return foo;}
    set {Foo = value;} // spot the typo!!! (should be foo)
}

从本质上讲,设置是:

static void set_Foo(int value) {
    set_Foo(value);
}

,所以这是递归的,并且最终会消耗堆栈向上(假定没有最佳化,等等)。

so this is recursive, and will eventually consume up the stack (assuming no optimisations, etc).

这是不可能的诊断多无一code样本。

It is impossible to diagnose more without a code sample.