gpt4 book ai didi

c# - 不完全确定如何使用接口(interface)进行多重继承 c#

转载 作者:行者123 更新时间:2023-11-28 03:13:31 25 4
gpt4 key购买 nike

我目前正在将游戏引擎的语言从 C++ 更改为 C#。在 C++ 中,我可以简单地在我的类中继承两个类,这使事情变得简单得多,但我发现这在 C# 中是不可能的。相反,我必须使用接口(interface)。

我四处寻找示例,我知道这里有很多;我不知道如何在我的案例中实现它。

请注意,我是按照教程生成此代码的,因此我对多态性的了解可能是错误的。

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++ 那样执行此操作,继承这两个类是行不通的。我认为这是我需要使用接口(interface)的地方。

public interface Transformable{ }
public interface Drawable : Transformable{ }

我想在 Drawable 类中我会实现虚拟绘图函数,但是,我实际上并没有实现 Transformable 的 getTransform 函数,所以我不知道如何像这样访问它。

有人可以告诉我如何使用接口(interface)通过我在此处提供的功能来执行此操作吗?

谢谢。

最佳答案

接口(interface)不能替代继承。

有了接口(interface),您就可以“继承”,嗯……一个接口(interface)。也就是说,一堆公共(public)成员(方法、属性)的签名。您实际上无法从接口(interface)继承任何有意义的内容。当您选择实现一个接口(interface)时,您给自己增加了一个负担,即您将要实现该接口(interface)的所有成员。它可以在设计阶段帮助您,但不会帮助您重用另一个类中已经存在的实现。

在C++中可以继承多个类是一个事实,在C#中可以实现多个接口(interface)也是一个事实。但是后者不是获取前者的 C# 方式。它们是两个不同的属性,两者都是正确的,一个是 C++ 语言,另一个是 C# 语言和 .NET 平台。

关于c# - 不完全确定如何使用接口(interface)进行多重继承 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17649318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com