简体   繁体   English

从公共实例属性返回静态属性的值

[英]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. 我只是在LINQPad中处理一些代码,并设法使程序出现stackoverflow异常而崩溃。

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. 我的instance属性的getter将返回静态字段的值,但是setter会自行设置。 When would this type of pattern be used and how come it generated a stackoverflow exception? 什么时候使用这种类型的模式?它为什么会产生stackoverflow异常?

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. 这是我对属性所做的第一件事:)-您递归地调用y setter而不是设置背景字段。 Since it calls itself, it will eventually stackoverflow. 由于它自己调用,因此最终将导致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; 您写了y = value; instead of x = value; 而不是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. 它将自动生成一个隐藏字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM