初始化类中的子类对象 - StackOverflowException [英] Initializing subclass object in class - StackOverflowException

查看:55
本文介绍了初始化类中的子类对象 - StackOverflowException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将代码剥离到导致问题的部分.代码在这里第5行和第9行来回跳转,导致stackoverflow异常.

I stripped my code to the parts that cause the problem. The code jumps back and forth lines 5 and 9 here, causing stackoverflowexception.

我怎么能以不同的方式做到这一点?我需要 Game 类中的 Platform 实例才能在函数中使用.

How could I do this differently? I need the Platform instance inside Game class to use in functions.

namespace Games
{
    public class Game
    {
        private Platform platform = new Platform();
    }
    class Platform : Game
    {
        private bool[] squares = new bool[9];
    }
}

推荐答案

当一个 Game 实例被创建时,它会创建一个 Platform 的实例,它会调用基类的构造函数它创建了一个 Platform 的实例,它将调用基类构造函数,它将...

When a Game instance is created it creates an instance of Platform which will invoke the base class constructor which creates an instance of Platform which will invoke the base class constructor which will...

看看这会导致什么?

您应该在尝试使用 Game 的地方使用 Platform.许多人会争辩说根本不使用继承.考虑在您的情况下可能意味着 Game 具有 Platform 类型的属性但 Platform 不继承自 Game 的组合.

You should use Platform where you are trying to use Game. Many would argue not to use inheritence at all. Consider composition which in your case might mean Game has a property of type Platform but Platform does not inherit from Game.

这篇关于初始化类中的子类对象 - StackOverflowException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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