Why does setting a static method result in a stack

2019-06-01 02:48发布

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.

标签: c# .net static
5条回答
混吃等死
2楼-- · 2019-06-01 02:51

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.

查看更多
姐就是有狂的资本
3楼-- · 2019-06-01 02:51

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.

查看更多
Juvenile、少年°
4楼-- · 2019-06-01 03:04

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.

查看更多
一纸荒年 Trace。
5楼-- · 2019-06-01 03:05

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.

查看更多
再贱就再见
6楼-- · 2019-06-01 03:12

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.

查看更多
登录 后发表回答