C# 堆栈溢出
我试图找出为什么会出现堆栈溢出异常。 我正在为学校作业创建一个简单的纸牌游戏,当我克隆纸牌以返回它们时,我收到堆栈溢出异常。
所以我得到了这个卡片类:
public class Card : ICloneable
{
....
#region ICloneable Members
public object Clone()
{
return this.Clone(); // <--- here is the error thrown when the first card is to be cloned
}
#endregion
}
并且我有一个名为 Hand
的类,然后它克隆卡片:
internal class Hand
{
internal List<Card> GetCards()
{
return m_Cards.CloneList<Card>(); // m_Cards is a List with card objects
}
}
最后,我得到了 List
的扩展方法:
public static List<T> CloneList<T>(this List<T> listToClone) where T : ICloneable
{
return listToClone.Select(item => (T)item.Clone()).ToList();
}
错误被抛出卡类(IClonable 方法),
CardLibrary.dll 中发生“System.StackOverflowException”类型的未处理异常
I am trying to find out why I am getting a stack overflow exception. I am creating a simple card game for a school assignment and when I clone the cards to return them I get the stack overflow exception.
So I got this card class:
public class Card : ICloneable
{
....
#region ICloneable Members
public object Clone()
{
return this.Clone(); // <--- here is the error thrown when the first card is to be cloned
}
#endregion
}
and I have a class called Hand
which then clones the cards:
internal class Hand
{
internal List<Card> GetCards()
{
return m_Cards.CloneList<Card>(); // m_Cards is a List with card objects
}
}
Last, I got an extension method for the List
:
public static List<T> CloneList<T>(this List<T> listToClone) where T : ICloneable
{
return listToClone.Select(item => (T)item.Clone()).ToList();
}
The error gets thrown in the card class (IClonable method),
An unhandled exception of type 'System.StackOverflowException' occurred in CardLibrary.dll
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你给自己打电话:
这会导致无限递归。
您的 Clone() 方法应该将所有属性/字段复制到一个新对象:
或者您可以使用 MemberwiseClone()
但这使您对克隆过程的控制较少。
You're calling yourself:
This results in infinite recursion.
Your Clone() method should copy all properties/fields to a new object:
or you could use MemberwiseClone()
But that gives you less control over the cloning process.
我倾向于对简单数据使用 MemberwiseClone() ,然后在我需要克隆的元素层次结构中实现 ICloneable ,因此:
其中 OrganizationLazyLoadPrefs 也在整个层次结构中实现 ICloneable 等等。
希望这可以帮助,
干杯,
特里
I've tended to use MemberwiseClone() for the simple data, and then implemented ICloneable throghout the hierarchy of elements that I've needed to clone, so:
Where OrganisationLazyLoadPrefs also implements ICloneable and so on and so forth throughout the hierarchy.
Hope this helps,
Cheers,
Terry