重载 getter 和 setter 导致 C# 中的堆栈溢出 [英] Overloading getter and setter causes a stack overflow in C#
问题描述
当我尝试覆盖 get 和 set 函数时,我不确定是什么导致了 StackOverflowException.当我只使用默认的 get 和 set 时,它就可以工作了.
I am not sure what is causing the StackOverflowException when I try to overwrite a get and set function. When I just use the default get and set it works.
enum MyEnumType
{
....
}
public MyEnumType data { get; set; }
但是当我尝试添加其他数据时,它会抛出 StackOverflowException:
But when I try to add additional data, it throws a StackOverflowException:
public MyEnumType data
{
get
{
return data;
}
set
{
data = value;
}
}
有什么想法吗?当我为 ASP.NET 用户控件属性执行此操作时,没有任何问题.为什么它会导致普通枚举数据类型的 StackOverflowException?
Any ideas? When I do this for ASP.NET user control attributes there isn't any problem. Why is it is causing a StackOverflowException for a normal enum data type?
推荐答案
是的,您没有支持字段...这就是您应该做的:
Yes, you do not have a backing field... this is how you should do it:
private MyEnumType data;
public MyEnumType Data
{
get
{
return data;
}
set
{
data = value;
}
}
发生的情况是您引用属性返回自身,这会导致尝试访问其自身值的无限循环.因此,堆栈溢出.
What happens is that you are referring to the property to return itself, which causes an infinite loop of trying to access its own value. Hence, a stack overflow.
在您没有在 get 和 set 方法中添加任何额外逻辑的情况下,您也可以使用自动属性.定义如下:
In your case when you do not add any additional logic in the get and set methods you could use an automatic property as well. This is simply defined like so:
public MyEnumType Data
{
get;
set;
}
这篇关于重载 getter 和 setter 导致 C# 中的堆栈溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!