我目前正在将游戏引擎的语言从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函数,所以我不知道如何像这样访问它。
有人能告诉我如何使用接口来完成这里提供的函数吗?
谢谢。
发布于 2013-07-15 16:40:39
接口不是继承的替代品。
有了你刚刚“继承”的接口,嗯……一个接口。也就是说,一组公共成员(方法、属性)的签名。实际上,您不能从接口继承任何有意义的内容。当你选择实现一个接口时,你给自己增加了一个负担,那就是你要实现接口的所有成员。它可以在设计阶段为您提供帮助,但不会帮助您重用已存在于另一个类中的实现。
在C++中可以从多个类继承是一个事实,在C#中可以实现多个接口是另一个事实。但是,后者不是获得前一种的C#方式。它们是两种不同的属性,都是真的,一种是C++语言,另一种是C#语言和.NET平台。
发布于 2013-07-15 23:52:23
在.NET中让X从Y继承可以完成两件很大程度上正交的事情:
X中可以使用父*对象实例*的protected实例成员或Y的静态protected成员,就像它们是自己的一样。类型为X的Y的实例的代码。一个对象只能有一个父对象实例;因此,一个对象只能使用从单个父类接收的受保护实例成员(这些成员可以在“祖父母”类中声明,但仍然通过父类接收)。由于从一个类继承会自动完成上述两个操作,这意味着类只能从一个类继承。然而,对于对象可以允许其自身被替换的类型的数量没有固有的限制。接口实现允许将实现接口的任何类型的对象传递给需要接口类型引用的任何代码。
https://stackoverflow.com/questions/17649318
复制相似问题