为什么属性集抛出异常计算器? [英] Why does Property Set throw StackOverflow exception?
问题描述
我知道Java和通常会放在getter / setter方法。我感兴趣的是在C#中使用以下code这样做,但它抛出一个异常计算器。我在做什么错了?
调用code
c.firstName =A;
属性code
公共字符串的firstName;
{
得到
{
返回的firstName;
}
组
{
的firstName =价值;
}
}
这是因为你在递归调用的属性 - 在设置
你重新设置该属性,它继续的循环往复的,直到你吹堆栈。
您需要的私人支持字段保存的价值,例如
私人字符串的firstName;公共字符串名字
{
得到
{
返回this.firstName;
}
组
{
this.firstName =价值;
}
}
另外,如果你正在使用C#3.0中,你可以使用自动属性,它会创建一个隐藏的后备字段,例如
公共字符串名字{获得;组; }
I know java and would normally put in getter/setter methods. I am interested in doing it in C# with the following code, but it throws a StackOverflow exception. What am I doing wrong?
Calling Code
c.firstName = "a";
Property Code
public String firstName;
{
get
{
return firstName;
}
set
{
firstName = value;
}
}
It's because you're recursively calling the property - in the set
you are setting the property again, which continues ad infinitum until you blow the stack.
You need a private backing field to hold the value, e.g.
private string firstName;
public string FirstName
{
get
{
return this.firstName;
}
set
{
this.firstName = value;
}
}
Alternatively, if you're using C# 3.0, you could use an auto-property, which creates a hidden backing field for you, e.g.
public string FirstName { get; set; }
这篇关于为什么属性集抛出异常计算器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!