简体   繁体   English

C#堆栈溢出

[英]C# stack overflow

I am trying to find out why I am getting a stack overflow exception. 我试图找出为什么我得到一个堆栈溢出异常。 I am creating a simple card game for a school assignment and when I clone the cards to return them I get the stack overflow exception. 我正在为学校作业创建一个简单的纸牌游戏,当我克隆纸牌以将其退还时,我会得到堆栈溢出异常。

So I got this card class: 所以我得到了这个卡类:

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
}

and I have a class called Hand which then clones the cards: 我有一个名为Hand的类,然后该类克隆了这些卡:

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

Last, I got an extension method for the List : 最后,我得到了List的扩展方法:

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

The error gets thrown in the card class (IClonable method), 该错误会在卡片类中抛出(IClonable方法),

An unhandled exception of type 'System.StackOverflowException' occurred in CardLibrary.dll CardLibrary.dll中发生了'System.StackOverflowException'类型的未处理异常

You're calling yourself: 您在自称:

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

This results in infinite recursion. 这导致无限递归。

Your Clone() method should copy all properties/fields to a new object: 您的Clone()方法应将所有属性/字段复制到新对象:

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

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

    return newCard;
}

or you could use MemberwiseClone() 或者您可以使用MemberwiseClone()

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

But that gives you less control over the cloning process. 但这使您对克隆过程的控制较少。

I've tended to use MemberwiseClone() for the simple data, and then implemented ICloneable throghout the hierarchy of elements that I've needed to clone, so: 我倾向于对简单的数据使用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();
    }
}

Where OrganisationLazyLoadPrefs also implements ICloneable and so on and so forth throughout the hierarchy. OrganisationLazyLoadPrefs还在整个层次结构中实现ICloneable等的地方。

Hope this helps, Cheers, Terry 希望这会有所帮助,干杯,特里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM