我在我的搜索中看到了很多可能的答案,甚至所有建议的答案都没有运气。我想我甚至可能不想继承。目前一切正常,这里有我的样本。
目前按预期工作:
public class PlayerShip : Sprite
{
public PlayerShip(Texture2D texture, Vector2 position, Rectangle boundry)
: base(texture, position, boundry, 2, 2, 14)
{
//Set some "PlayerShip" specific properties
}
}
public class Sprite //The Base Class
{
public Sprite(Texture2D texture, Vector2 position, Rectangle boundry) : this(texture, position, boundry, 1, 1, 1)
{}
public Sprite(Texture2D texture, Vector2 position, Rectangle boundry, int rows, int cols, double framesPerSecond)
{
//Set a bunch of properties here
}
//other methods with virtual keyboard that I can override if I choose
}
当我想要更改要加载的PlayerShip类而不使用“texture”参数代替其他内容时,会出现问题。我想在PlayerShip构造函数中加载“texture”参数,删除Position参数,然后将其传递给基础。我不能在基础构造函数上使用虚拟或抽象来覆盖,我得到一个错误,我必须有“纹理”
所以这失败了:
public PlayerShip(ContentManager content, Rectangle boundry)
{
base(content.Load<Texture2D>("Image"), boundry);
//Set some "PlayerShip" specific properties
}
错误:在行基础上预期的方法,委托或事件。但我不能这样做:基础方式因为纹理不是参数的一部分。
然后我想我会把它放在基础上,但我不希望它在基础上,因为我只想要一些继承的类来使用这个新参数。因为我不知道它的值是什么,所以我必须把它装空。但我无法像这样调用原始构造函数
public Sprite(ContentManager content, Rectangle boundry)
: this(content.Load<Texture2D>(""), position, boundry) //<-- Error position doesn't exist
{
}
所以我想我会尝试类似的东西,如果我能做到这一点,这会很有效
public Sprite(ContentManager content, Rectangle boundry)
{
//load up texture with content and get position
Sprite(texture, position, boundry); //<-- Method, delegate or event is expected
}
似乎我可以绕过它的唯一方法是有两个构造函数来初始化所有相同的参数。除了..如果我尝试这个...在我可以在继承类中设置属性之前调用基类。
public PlayerCat(ContentManager content, Rectangle deviceBounds)
: base(deviceBounds, 2, 4, 20)
{
//set all my properties
}
public Sprite(Rectangle deviceBounds)
: this(deviceBounds, 1, 1, 1)
{
}
public Sprite(Rectangle deviceBounds, int rows, int cols, double framesPerSecond)
{
//Properties Error out here because they are called before I get to set them
}
答案 0 :(得分:1)
将初始化代码移动到从构造函数调用的普通方法。这允许您以任何顺序调用它们。
public class Sprite
{
public Sprite(Texture2D texture, Vector2 position, Rectangle boundry)
: this(texture, position, boundry, 1, 1, 1)
{
}
public Sprite(Texture2D texture, Vector2 position, Rectangle boundry,
int rows, int cols, double framesPerSecond)
{
Initialize(texture, position, boundry, rows, cols, framesPerSecond);
}
public Sprite(ContentManager content, Rectangle boundry)
{
//TODO: Load up texture with content and get position
Initialize(texture, position, boundry);
}
private void Initialize(Texture2D texture, Vector2 position, Rectangle boundry,
int rows, int cols, double framesPerSecond)
{
//TODO: Set a bunch of properties here
}
private void Initialize(Texture2D texture, Vector2 position, Rectangle boundry)
{
Initialize(texture, position, boundry, 2, 2, 14);
}
}