问题
I have been writing some code in the Unity3d engine and have been teaching myself C#. I have been trying to find an answer to my question but to no avail. I've come from java and been trying to use properties and I'm afraid that I don't understand them very well. When I tried something like this:
public int Property
{
get
{
return Property;
}
set
{
Property = value;
}
}
I get a stack overflow initializing the object when that property is accessed for assignment. I was able to fix it by just using the default property style:
get;
set;
but I don't know what is going on in the first instance that is causing the exception. It would be fantastic if someone could help explain this.
回答1:
You need a backing field.
When you set that property, it will set itself, which will set itself, which will set itself, which will set itself, which will ... you get the gist.
Either:
private int _Property;
public int Property
{
get
{
return _Property;
}
set
{
_Property = value;
}
}
or this:
public int Property
{
get;
set;
}
This latter form, called an automatic property, creates that backing field for you so in reality these two will create nearly the same code (the name of the backing field will differ).
When you do this in your version of the code:
x.Property = 10;
you end up the property doing the exact same thing, and thus you get a stack overflow. You could rewrite it to a method with the same problem like this:
public void SetProperty(int value)
{
SetProperty(value);
}
This tool will cause a Stack Overflow Exception for the exact same reason.
回答2:
Moreover remember that when you are creating a property like this
public class Example
{
public String MyData{ get; set;}
}
Actually when you compile it the compiler translate it to something like this:
public class Example
{
private String _myData;
public String MyData{ get {return _myData}; set { _myData = value}}
}
来源:https://stackoverflow.com/questions/30389870/user-defined-properties-in-c-sharp-cause-stackoverflowexception-on-construction