[英]C# getter/setter pairs
I am trying to create a property i with the following getter and setter. 我正在尝试使用以下getter和setter创建属性。 I have tried:
我努力了:
int i {
get{
return i;
}
set {
if (value > 60) {
} else {
i = value;
}
}
}
However, when I try this I get a stack overflow error when I try to run the code. 但是,当我尝试这个时,我尝试运行代码时出现堆栈溢出错误。 Is there anything wrong with my code?
我的代码有什么问题吗? Any Assistane would be appreciated.
任何Assistane将不胜感激。
You need a backing field if you have any kind of logic in your property (otherwise automatic properties are the way to go) - currently you are assigning to the property itself which again calls your setter code (likewise for the getter) - that causes the Stackoverflow exception. 如果你的属性中有任何类型的逻辑,你需要一个支持字段(否则自动属性是要走的路) - 目前你正在分配给属性本身再次调用你的setter代码(同样对于getter) - 这会导致Stackoverflow异常。
Example: 例:
private int _i;
public int SomeProperty
{
get{ return _i;}
set
{
//your logic here
_i = value;
}
}
Do this: 做这个:
private int i; // backing field
int I
{
get
{
return i;
}
set
{
if (value > 60) {
} else
{
i = value;
}
}
}
If you do not do this, your code will be kept in a cyclic state and hence the StackOverflow
error. 如果不这样做,您的代码将保持循环状态,从而导致
StackOverflow
错误。
Its this way 就是这样
private int i = 0;
public int I
{
get
{
return i;
}
set
{
if (value > 60)
{
}
else
{
i = value;
}
}
}
and please follow some coding naming conventions where 并请遵循一些编码命名约定
Simply use this piece of code: 只需使用这段代码:
int i;
public int I
{
get { return i; }
set { if (value <= 60) i = value; }
}
The problem in your code is that you specified i in the Property which was referring to itself inside the body of getter/setter, turning to be cyclic effect, and eventually StackOverflow error. 您的代码中的问题是您在属性中指定了i,它在getter / setter体内引用了自身,转为循环效果,最终导致StackOverflow错误。
int i {
get{
return i;
}
set {
...
i = value;
...
}
}
In your code above, you are using the same property name inside get and set blocks. 在上面的代码中,您在get和set块中使用相同的属性名称。
After compilation, your code will be translated to some thing equivalent to this: 编译后,您的代码将被转换为与此相当的东西:
int get_i()
{
return get_i();
}
void set_i(int value)
{
set_i(value);
}
As you can see each of them will call itself (recursion) infinitely without any exit condition, resulting into a StackOverflow
exception. 正如您所看到的,每个都将无限地调用自身(递归)而没有任何退出条件,从而导致
StackOverflow
异常。
If you have a backing field to the property, like how other answers to this question have suggested, the compiler would generate some thing equivalent to this, which has no recursion: 如果你有一个属性的支持字段,就像这个问题的其他答案所提出的那样,编译器会生成一些与此相当的东西,它没有递归:
int get_i()
{
return _i; //_i is the backing field
}
void set_i(int value)
{
_i = value;
}
UPDATE: 更新:
For completeness, I am adding here a way to solve your problem. 为了完整起见,我在这里添加了一种解决问题的方法。
int _i;
int i {
get{
return _i;
}
set {
if (value > 60) {
} else {
_i = value;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.