在基础构造函数中使用'this'?

Wil*_*mas 16 c# inheritance constructor base this

我的工作,涉及到了很多接口和继承,它开始变得有点棘手的项目,现在我碰到的一个问题.

我有一个抽象类State,它接受一个Game对象作为构造函数参数.在我的Game类的构造函数中,它接受一个State.这个想法是,当从抽象基类Game类继承时,在调用基类的构造函数时,你给它一个初始的State对象.但是,此State对象与您正在创建它的游戏相同.代码如下所示:

public class PushGame : ManiaGame
{
     public PushGame() :
          base(GamePlatform.Windows, new PlayState(this), 60)
     {
     }
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用.我只能假设因为'this'关键字在构造函数开始执行之后才可用.试图在基类的构造函数中使用它显然不起作用.那么对我来说最好的解决方法是什么呢?我的计划B是从Game类的构造函数中删除State参数,然后在构造函数代码中设置状态.

这样做有一种更简单,更少侵入性的方式吗?

Adr*_*ode 8

显然,ManiaGame类总是使用PlayState类型的对象,因此您可以在ManiaGame级别移动创建:

public class PushGame : ManiaGame
{
     public PushGame() : base()
     {
     }

}

public class ManiaGame
{
    PlayState ps;   
    public ManiaGame() {
        ps = new PlayState(this);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你想要更具体的PlayState类..

public class PushGame : ManiaGame
{
     public PushGame() : base()
     {
     }
     protected override PlayState CreatePlayState()
     {
        return new PushGamePlayState(this);
     }
}

public class ManiaGame
{
    PlayState ps;   
    public ManiaGame() {
          ps = CreatePlayState();
    }
    protected virtual PlayState CreatePlayState()
    {
        return new PlayState(this);
    }
}

public class PlayState
{
   public PlayState(ManiaGame mg) {}
}


public class PushGamePlayState : PlayState
{
   public PushGamePlayState(ManiaGame mg) : base(mg){}
}
Run Code Online (Sandbox Code Playgroud)

  • 值得一提的是,从ctor内部调用虚拟方法可能很危险 - http://stackoverflow.com/questions/119506/virtual-member-call-in-a-constructor (2认同)