开发者

Returning value of static property from public instance property

I was just playing around with some code in LINQPad and managed to crash the program with a stackoverflow exception.

I basically created a static property in a field and used a property to return the value from an instance.

The getter of my instance property would return the value of the static field, but the setter would set itself. When wou开发者_StackOverflow中文版ld this type of pattern be used and how come it generated a stackoverflow exception?

Code example of what I did:

void Main()
{
    SomeClass myinstance = new SomeClass();
    SomeClass.x = "Some Value";
    myinstance.y = "Some other value";
    myinstance.y.Dump();
}

public class SomeClass
{
    public static string x;

    public string y
    {
        get { return x; }
        set { y = value; }
    }
}


This is the first thing I ever did with properties :) -- you're recursively calling the y setter rather than setting a backing field. Since it calls itself, it will eventually stackoverflow.

Each setter is syntactic sugar and is basically a method call. What you've done is basically equivalent to doing this with a method:

public class SomeClass
{
   public string GetValue() { return "some string"; }
   public void SetValue(string arg)
   { 
       SetValue(arg); // recursively calls itself until stackoverflow
   }
}


You wrote y = value; instead of x = value; in the setter!

Note, that for simple properties you can use

public string y { get; set; }

Which will automatically generate a hidden field.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜