【发布时间】:2013-12-17 07:44:22
【问题描述】:
我在搜索中查看了很多可能的答案,甚至在我输入此内容时建议的所有答案都没有运气。我想我什至可能不想要继承。目前一切正常,这是我所拥有的样本。
目前按预期工作:
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 构造函数中加载“纹理”参数,删除 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
}
【问题讨论】:
标签: c# inheritance