从抽象基类的重写属性抛出的堆栈溢出异常 [英] Stack overflow exception thrown from overridden property from abstract base class
问题描述
我有一个带有以下(为简洁起见进行了修剪)声明的基类:
I have a base class with the following (trimmed for brevity) declaration:
public abstract class MyBaseClass
{
public int RecordId { get; private set; }
public string ObjectName { get; set; }
public abstract string Status { get; set; }
public GetMyObject(int id)
{
MyObject myObject = context.GetObjectById(id);
this.RecordId = myObject.RecordId;
this.ObjectName = myObject.ObjectName;
this.Status = myObject.Status
}
}
由以下类使用:
public class MySpecificClass : MyBaseClass
{
public override string Status
{
get
{
if(this.Status == "something")
return "some status";
else
return "some other status";
}
set
{
this.Status = value;
}
}
public GetMySpecificObject(int id) : base(id)
{
}
}
现在,当我将我的特定对象绑定到我的模型时(我的实现恰好是 MVC),如果我只访问 RecordID 和 ObjectName,该对象返回就好了,但是如果 get 或 set 访问器,我会收到堆栈溢出异常到我的(被覆盖的)状态被击中.
Now when I bind my specific object to my model (my implementation happens to be MVC) the object is returned just fine if I only access the RecordID and the ObjectName, but I get a stack overflow exception if the get or set accessors to my (overridden) Status is hit.
我已经在 SO 上发现了一个类似的问题...
I found a similar question on SO already...
为什么 Property Set 会抛出 StackOverflow 异常?
...但是通过自动属性实现,我的代码看起来是正确的并且不会创建无限循环(但情况似乎确实如此).关于如何正确覆盖该属性的任何想法?
... but going by the auto-property implementation, my code looks like it would be correct and not create an infinite loop (but this does appear to be the case). Any ideas on how I would correctly override that property?
谢谢!
推荐答案
MySpecificClass 中的 setter 应该没有问题,但 getter 肯定是 - 在内部,对 MySpecificClass 的 Status 实例的调用将调用自己看看要返回哪个值,这将调用自己来查看......好吧.你懂的.
The setter in MySpecificClass shouldn't be a problem, but the getter definitely is - internally, a call to an instance of MySpecificClass's Status will be making a call to itself to see which value to return which will make a call to itself to see... well. You get the idea.
我会使用受保护的类变量而不是自动属性.
I'd use a protected class variable rather than an auto-property.
public abstract class MyBaseClass
{
protected string _status;
public virtual string Status
{
get { return _status; }
set { _status = value; }
}
}
public class MySpecificClass : MyBaseClass
{
public override string Status
{
get
{
if(_status == "something")
return "some status";
else
return "some other status";
}
set
{
_status = value;
}
}
}
这篇关于从抽象基类的重写属性抛出的堆栈溢出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!