gpt4 book ai didi

c# - 实现 "Inherit"(实现)通用接口(interface)的接口(interface)?

转载 作者:太空狗 更新时间:2023-10-30 00:52:27 29 4
gpt4 key购买 nike

interface ITurtle
{
void Fight();
void EatPizza();
}

interface ILeonardo : ITurtle
{
void UseKatana();
}

interface IRaphael : ITurtle
{
void UseSai();
}

interface IDonatello : ITurtle
{
void UseBo();
}

interface IMichelangelo : ITurtle
{
void UseNunchuku();
}

如果我想创造一只可以做到所有 4 项的大乌龟怎么办?我想编码:

class GrandTurtle : IMichelangelo, IDonatello, IRaphael, ILeonardo
{
// Implementation not shown for brevity.
}

这可能吗,因为现在,我似乎必须分别执行 Fight()EatPizza() 4 次。但我认为这两个通用功能将解决并且只需要实现一次,对吧?

我可以在不继承 ITurtle 的情况下创建 4 个中间接口(interface),然后让 GrandTurtle 实现 ITurtle。这解决了接口(interface)继承问题,但现在它在语义上看起来是错误的,因为它使 ITurtle 看起来像第五兄弟,但事实并非如此。另外,我希望能够创建特定于乌龟的类,例如 class BostonLeonardo : ILeonardo

我从很多地方读到这似乎是一场无休止的辩论 - 有人说“接口(interface)内的继承”非常好,而有人说它不是 - 要么我不理解他们的解释,要么他们只是说这很糟糕练习而不解释原因。

最佳答案

您只能实现方法 FightEatPizza 一次,因为只有一个接口(interface)定义了它们。如果您在每个 ILeonardo 等接口(interface)上都​​有 FightEatPizza,您可以选择实现一次或使用显式接口(interface)根据接口(interface)签名更改这些方法的行为的实现。我会举个例子,因为我喜欢 TMNT:

interface ILeonardo
{
void Fight();
void EatPizza();
void UseKatana();
}

interface IRaphael
{
void Fight();
void EatPizza();
void UseSai();
}

interface IDonatello
{
void Fight();
void EatPizza();
void UseBo();
}

interface IMichelangelo
{
void Fight();
void EatPizza();
void UseNunchuku();
}

class GrandTurtle : IMichelangelo, IDonatello, IRaphael, ILeonardo
{
// Code that fires when Fight is called on ILeonardo turtle = new GrandTurtle()
void ILeonardo.Fight()
{
UseKatana();
}

// Code that fires when Fight is called on IRaphael turtle = new GrandTurtle()
void IRaphael.Fight()
{
UseSai();
}

// Code that fires for all other turtles
public void Fight()
{
UseThatCrappyStickThingTheOldActionFiguresCameWith();
}

// Implement EatPizza() and such here...
}

只有当 GrandTurtle 的类型签名是适当的接口(interface)时,这些显式接口(interface)实现才会生效。

关于c# - 实现 "Inherit"(实现)通用接口(interface)的接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21324264/

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