重载getter和setter会导致C#中的堆栈溢出 [英] Overloading getter and setter causes a stack overflow in C#
问题描述
当我尝试覆盖get and set函数时,我不确定是什么导致StackOverflowException.当我只使用默认的get并进行设置时就可以使用.
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屋!