Getter C# 上的 StackOverflowException [英] StackOverflowException on Getter C#

查看:18
本文介绍了Getter C# 上的 StackOverflowException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在抽象类中的属性的 get; 上收到 StackOverflowException.

I am getting a StackOverflowException on the get; of a property in an abstract class.

public abstract class SenseHatSnake
    {

        private readonly ManualResetEventSlim _waitEvent = new ManualResetEventSlim(false);

        protected SenseHatSnake(ISenseHat senseHat)
        {
            SenseHat = senseHat;
        }

        protected static ISenseHat SenseHat { get; set; } // This Line

        public virtual void Run()
        {
            throw new NotImplementedException();
        }

        protected void Sleep(TimeSpan duration)
        {
            _waitEvent.Wait(duration);
        }

    }

我正在这里设置并获取它:

I am setting and getting it here:

public class SnakeGame : SenseHatSnake
{
    private readonly int _gameSpeed = 1000;
    private static Timer _updatePositionTimer;
    private bool _gameOver = false;

    public readonly Movement Movement = new Movement(SenseHat);
    public readonly Food Food = new Food(SenseHat);
    public readonly Body Body = new Body(SenseHat);
    public readonly Display Display = new Display(SenseHat);
    public readonly Draw Draw = new Draw(SenseHat);

    public SnakeGame(ISenseHat senseHat)
        : base(senseHat)
    {
    }
    //More code
}

其中一个类如下所示:

public class Movement : SnakeGame
{

    public Movement(ISenseHat senseHat)
        : base(senseHat)
    {
    }
    //More code
}

据我所知,StackOverflowException 意味着我在某个地方有一个无限循环或无限递归,但老实说我不知道​​在哪里,也不知道如何解决它.

To my knowledge a StackOverflowException means I somewhere have an an infinite loop or infinite recursion, but I honestly don't know where, nor do I know how to solve it.

推荐答案

SnakeGame 中的这一行导致递归

public readonly Movement Movement = new Movement(SenseHat);

由于Movement继承自SnakeGame,所以它的构造函数会初始化SnakeGame,再次调用上面那行来初始化它自己的Movement 字段.这导致递归.

Since Movement is inherited from SnakeGame, its constructor will initialize SnakeGame, calling the line above again to initialize its own Movement field. That results into recursion.

这篇关于Getter C# 上的 StackOverflowException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆