2009-07-29 144 views
1

我想知道为什么我得到堆栈溢出异常。我为学校作业创建了一个简单的纸牌游戏,当我克隆卡片返回它们时,我得到了堆栈溢出异常。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

+2

做卡需要是可变的,即他们有状态,可以改变吗?如果没有,那么你可以拥有一套不可变的卡片,你可以在不同的收藏中重复使用。不需要克隆。 – pjp 2009-07-29 09:42:08

+0

请参阅关于ICloneable的讨论:http://stackoverflow.com/questions/699210/why-should-i-implement-icloneable-in-c – peterchen 2009-07-29 09:57:41

+0

阅读这个问题的标题后,我认为这属于元。 ..--) – EricSchaefer 2009-07-29 10:04:35

回答

22

你调用自己:

public object Clone() 
{ 
    return this.Clone(); 
} 

这导致无限递归。

你的clone()方法应该所有属性/字段复制到一个新的对象:

public object Clone() 
{ 
    Card newCard = new Card(); 

    newCard.X = this.X; 
    // ... 

    return newCard; 
} 

,或者您可以使用MemberwiseClone()

public object Clone() 
{ 
    return MemberwiseClone(); 
} 

但是,让您在克隆较少的控制处理。

0

我倾向于使用MemberwiseClone()的简单的数据,然后执行ICloneable throghout,我已经需要克隆元素的层次结构,所以:

public class CRMLazyLoadPrefs : ICloneable 
{ 
    public bool Core { get; set; } 
    public bool Events { get; set; }  
    public bool SubCategories { get; set; } 
    public OrganisationLazyLoadPrefs { get; set; } 

    public object Clone() 
    { 
     CRMLazyLoadPrefs _prefs = new CRMLazyLoadPrefs(); 
     // firstly, shallow copy the booleans 
     _prefs = (CRMLazyLoadPrefs)this.MemberwiseClone(); 
     // then deep copy the other bits 
     _prefs.Organisation = (OrganisationLazyLoadPrefs)this.Organisation.Clone(); 
    } 
} 

凡OrganisationLazyLoadPrefs也实现ICloneable和等等等等。

希望这有助于 干杯, 特里