【发布时间】:2013-07-15 07:57:18
【问题描述】:
我目前正在将我的游戏引擎的语言从 c++ 更改为 c#。在 c++ 中,我可以简单地在我的类中继承两个类,这使事情变得更简单,但是我发现这在 c# 中是不可能的。相反,我必须使用接口。
我已经四处寻找示例,我知道这里有很多;我不知道如何在我的情况下实现它。
请注意,我是按照教程生成此代码的,因此我对多态性的了解可能是错误的。
C++ 代码:
class TileMap : public sf::Drawable, public sf::Transformable
{
...
private:
//this virtual function is simply so we don't have to do window.draw(target, states), we can just do window.draw(instance)
//this is called polymorphism?
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const
{
// apply the transform
//this isn't our method, i assume it's something in draw() by default.
//or this generates the finished quads in one image instead of multiple ones.
states.transform *= getTransform();
// apply the tileset texture
//this puts the texture on to what we're going to draw (which is converted in to a single texture)
states.texture = &m_tileset;
// draw the vertex array
target.draw(m_vertices, states);
}
}
我的 tilemap 类继承了 Drawable 类。 states.transform *= getTransform() 意味着我需要继承 Transformable 类。
但是,我不能像 c++ 一样在 c# 中执行此操作,继承这两个类是行不通的。 我认为这就是我需要使用接口的地方。
public interface Transformable{ }
public interface Drawable : Transformable{ }
我想在 Drawable 类中我会实现虚拟绘图功能,但是,我实际上并没有从 Transformable 实现 getTransform 函数,所以我不知道如何像这样访问它。
有人可以告诉我如何使用接口来使用我在此处提供的功能吗?
谢谢。
【问题讨论】:
-
也许你有兴趣阅读composition over inheritance。
-
您的“Drawable”接口不需要实现“Transformable”:至少在您发布的 C++ 代码中并不明显。有 2 个独立的接口,并在您的 TileMap 类中实现它们。正如 Corak 建议的那样,您还应该检查是否可以编写一些行为。
-
感谢@Corak @aquaraga 使用接口让我感到困惑的一件事是我实际上并没有为
getTransform提供实现,我使用的是我继承的类中的实现。因此,我不知道如何让它在这种情况下工作。您认为如果可能的话,您可以向我展示如何实现此功能的示例吗?谢谢。
标签: c# c++ inheritance interface polymorphism