Why does setting a static method result in a stack

2019-06-01 02:36发布

问题:

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.

回答1:

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)
}

Essentially, the set is:

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

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

It is impossible to diagnose more without a code sample.



回答2:

I'm guessing you're doing something like this:

public class MyClass
{
    public int TheInt
    {
    get
    {
        return TheInt;
    }
    set
    {
        TheInt = value; // assignment = recursion!
    }
}

The problem is, in the set function for TheInt, you're assigning a value to TheInt which will result in a nested call to the set function. You get recursion, and then a stack overflow.



回答3:

Look at your call stack in the debugger (you do stop when exceptions are thrown, right?) This should give you a strong indication of what's going on.



回答4:

I think I see a different interpretation of the question. Where the question isn't why the overflow happens, but why accessors can cause overflows. In this case, the accessor is a function call just like any other, and so it does consume stack space.

If you're using public members with no accessors, MyClass.myint doesn't become a function call, and can't overflow the stack.



回答5:

You want to know what's going on in the internals to cause the stack overflow?

Your method calls another method that results in infinite recursion: A calls A, stack overflow. A calls B, then B calls A, stack overflow. And so on.

As Marc Gravell suggested, it's likely theres a bug in your property implementation.



标签: c# .net static