C# 为什么 Property Set 会抛出 StackOverflow 异常?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/367192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does Property Set throw StackOverflow exception?
提问by Adam Lerman
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?
我知道 java 并且通常会放入 getter/setter 方法。我有兴趣使用以下代码在 C# 中执行此操作,但它会引发 StackOverflow 异常。我究竟做错了什么?
Calling Code
呼叫代码
c.firstName = "a";
Property Code
属性代码
public String firstName;
{
get
{
return firstName;
}
set
{
firstName = value;
}
}
采纳答案by Greg Beech
It's because you're recursively calling the property - in the set
you are setting the property again, which continues ad infinitumuntil you blow the stack.
这是因为您正在递归调用该属性 - 在set
您再次设置该属性时,它会无限地继续,直到您炸毁堆栈。
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.
或者,如果您使用的是 C# 3.0,您可以使用自动属性,它会为您创建一个隐藏的支持字段,例如
public string FirstName { get; set; }
回答by Michael Haren
You are setting the property name inside your property--not the field name. This would work better:
您正在属性中设置属性名称 - 而不是字段名称。这样效果会更好:
private string m_firstName;
public String firstName;
{
get
{
return m_firstName;
}
set
{
m_firstName = value;
}
}