1

我试图找出为什么会出现堆栈溢出异常。我正在为学校作业创建一个简单的纸牌游戏,当我克隆卡片以返回它们时,我得到了堆栈溢出异常。

所以我得到了这个卡片类:

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”类型的未处理异常

4

2 回答 2

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();
}

但这使您对克隆过程的控制较少。

于 2009-07-29T09:23:15.333 回答
0

我倾向于将 MemberwiseClone() 用于简单数据,然后通过我需要克隆的元素层次结构实现 ICloneable,因此:

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 等等。

希望这会有所帮助,干杯,特里

于 2009-07-29T10:00:28.470 回答