gpt4 book ai didi

使用派生接口(interface)的 C# 接口(interface)实现

转载 作者:太空宇宙 更新时间:2023-11-03 18:22:59 24 4
gpt4 key购买 nike

在下面的示例类中,“SomeClass”没有实现“ISomeInterface”。为什么我不能通过传递一个实现基本要求的更派生的接口(interface)来实现这一点。无论传递什么实例,它仍然会实现基础,我是否遗漏了什么?

namespace Test
{
public interface IBaseInterface
{
void DoBaseStuff();
}

public interface IChildInterface : IBaseInterface
{
void DoChildStuff();
}

public interface ISomeInterface
{
void DoSomething(IBaseInterface baseInterface);
}

public class SomeClass : ISomeInterface
{
public void DoSomething(IChildInterface baseInterface)
{
}
}
}

最佳答案

存在此限制是因为 ISomeInterface 期望任何 IBaseInterface 都将满足契约。也就是说,如果您有以下条件:

public interface IBase {}
public interface IChildA : IBase {}
public interface IChildB : IBase {}

还有一个需要 IBase 的接口(interface):

public interface IFoo { void Bar(IBase val); }

然后根据需要在派生类中限制它:

public class Foo : IFoo { public void Bar(IChildA val) {} }

会产生以下问题:

IChildB something = new ChildB();
IFoo something = new Foo();
something.Bar(something); // This is an invalid call

因此,您没有执行您所说的契约(Contract)。

在这种情况下,您有两个简单选项:

  • IFoo 调整为通用的,并接受 IBase 的派生 T:

    public interface IFoo<T> where T : IBase { void Bar(T val); }
    public class Foo : IFoo<IChildA> { public void Bar(IChildA val) {} }

    当然,这意味着Foo不能再接受任何 IBase(包括IChildB)。

  • 调整 Foo 以实现 IFoo,为 void Bar(IChildA val) 添加一个实用方法:

    public class Foo : IFoo
    {
    public void Bar(IBase val) {}
    public void Bar(IChildA val) {}
    }

    这有一个有趣的副作用:每当您调用 ((IFoo)foo).Bar 时,它会期待 IBase,而当您调用 foo 时。 Bar 它将期望 IChildA IBase。这意味着它满足契约(Contract),同时还具有您的派生接口(interface)特定方法。如果你想更多地“隐藏”Bar(IBase) 方法,你可以显式实现 IFoo:

    void IFoo.Bar(IBase val) { }

    这会在您的代码中产生更多不一致的行为,因为现在((IFoo)foo).Bar 完全不同于foo.Bar,但我把决定权交给你。

    这意味着,在本节的第二个版本中,foo.Bar(new ChildB()); 现在无效,因为 IChildB 不是 IChildA


Why can't I implement this by passing a more derived interface which does implement the base requirement. Whatever instance would be passed it would still implement the base, am I missing something?

由于我上面提到的原因,这是不允许的,IFoo.Bar 期望 any IBase,而您想要 进一步将类型限制为IChildA不是 IBase 的 super 接口(interface),即使是也不会被允许,因为它违反了接口(interface)实现,尽管您可以更轻松地在此时定义第二个方法来执行您想要的操作。

请记住,当您实现一个接口(interface)时,您就订阅了一个契约(Contract),而 C# 将不会让您违反该契约(Contract)。

关于使用派生接口(interface)的 C# 接口(interface)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45221215/

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