C#堆栈溢出

Pat*_*ick 1 c# stack-overflow icloneable

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

所以我得到了这个卡类:

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
}
Run Code Online (Sandbox Code Playgroud)

我有一个叫做Hand克隆的课程:

internal class Hand
{
        internal List<Card> GetCards()
        {
            return m_Cards.CloneList<Card>(); // m_Cards is a List with card objects
        }
}
Run Code Online (Sandbox Code Playgroud)

最后,我得到了一个扩展方法List:

    public static List<T> CloneList<T>(this List<T> listToClone) where T : ICloneable
    {
        return listToClone.Select(item => (T)item.Clone()).ToList();
    }
Run Code Online (Sandbox Code Playgroud)

错误被卡类(IClonable方法)抛出,

CardLibrary.dll中发生了未处理的"System.StackOverflowException"类型异常

Phi*_*ert 22

你在打电话给自己:

public object Clone()
{
    return this.Clone();
}
Run Code Online (Sandbox Code Playgroud)

这导致无限递归.

您的Clone()方法应将所有属性/字段复制到新对象:

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

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

    return newCard;
}
Run Code Online (Sandbox Code Playgroud)

或者你可以使用MemberwiseClone()

public object Clone()
{
    return MemberwiseClone();
}
Run Code Online (Sandbox Code Playgroud)

但这使您无法控制克隆过程.