我想知道为什么我得到堆栈溢出异常。我为学校作业创建了一个简单的纸牌游戏,当我克隆卡片返回它们时,我得到了堆栈溢出异常。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();
}
卡类错误(ICl onable法),
类型 'System.StackOverflowException' 未处理的异常发生在CardLibrary.dll
做卡需要是可变的,即他们有状态,可以改变吗?如果没有,那么你可以拥有一套不可变的卡片,你可以在不同的收藏中重复使用。不需要克隆。 – pjp 2009-07-29 09:42:08
请参阅关于ICloneable的讨论:http://stackoverflow.com/questions/699210/why-should-i-implement-icloneable-in-c – peterchen 2009-07-29 09:57:41
阅读这个问题的标题后,我认为这属于元。 ..--) – EricSchaefer 2009-07-29 10:04:35