【发布时间】:2009-07-29 09:21:02
【问题描述】:
我正在尝试找出为什么会出现堆栈溢出异常。我正在为学校作业创建一个简单的纸牌游戏,当我克隆卡片以返回它们时,我得到了堆栈溢出异常。
所以我得到了这个卡片类:
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”类型的未处理异常
【问题讨论】:
-
卡片是否需要可变,即它们是否具有可以更改的状态?如果没有,那么您可以只拥有一组可以在不同集合中重复使用的不可变卡片。无需克隆。
-
另请参阅有关 ICloneable 的讨论:stackoverflow.com/questions/699210/…
-
在阅读了这个问题的标题后,我认为这属于元... ;-)
标签: c# stack-overflow icloneable