【问题标题】:How to implement two methods one from each interfaces which contain more method definition? [closed]如何从每个包含更多方法定义的接口中实现两种方法? [关闭]
【发布时间】:2020-02-20 20:21:06
【问题描述】:
interface Ia 
{
    void m1();
    void m2();
}

interface Ib
{
    void m3();
    void m4();
}

这里如何在一个类中实现m1和m3?

【问题讨论】:

  • 你必须全部实现。如果我说我是IaIb,那么我必须能够做到这四个(或者我在撒谎——编译器会抱怨这是可以理解的)。 此外,如果您使用有意义的接口和方法名称,这些类型的问题更容易讨论。
  • 你尝试过什么,失败的原因是什么?
  • 您无法选择要实现的接口成员。实现类型必须为接口的所有成员提供一个实现(即使该类型是抽象的,它也必须至少提供一个抽象成员)。接口类似于合约,如果代码可以选择要实现的合约的哪些部分,它将不再是有效的合约。
  • 如果你只使用一个,你应该将它们分成多个接口。您可以同时实现两者并抛出NotSupportedException(),但这是一种不好的编程习惯,因为它违反了 SOLID 原则。
  • 接口是一个CONTRACT,你必须实现接口中的所有方法。接口是实现多态性的一种方式。更多信息:docs.microsoft.com/en-us/dotnet/csharp/language-reference/…

标签: c# oop


【解决方案1】:

假设您有一个继承自两个接口的类 - 在这种情况下,您还需要在 m1()m3() 旁边实现 m2()m4()

interface Ia
{
    void m1();
    void m2();
}

interface Ib
{
    void m3();
    void m4();
}


public class Ca : Ia , Ib
{
    public void m1() { }
    public void m2() { throw new NotImplementedException();  }
    public void m3() { }
    public void m4() { throw new NotImplementedException();  }
}

您不能只从接口中选择一些方法作为类的一部分——它们都必须被实现。我会改变你接口的架构,或者如果你不能访问这个代码,你可以用 NotImplementedException() 来实现它们

【讨论】:

  • 正如我的评论中提到的,你可以,但你不应该这样做。见en.wikipedia.org/wiki/Interface_segregation_principle
  • @NibblyPig 对,这不是好的做法,应该被视为最后的出路。无论如何,我会使用 NotImplementedException 而不是 NotSupportedException
  • NotSupportedException 在这种情况下是首选,You might choose to throw a NotImplementedException exception in properties or methods in your own types when the that member is still in development and will only later be implemented in production code. In other words, a NotImplementedException exception should be synonymous with "still in development."Throw a NotSupportedException exception if the implementation of an interface member or an override to an abstract base class method is not possible. 来自 docs.microsoft.com/en-us/dotnet/api/…
【解决方案2】:

您无法选择要实现的成员,您必须实现每个接口成员。如果您需要对要实现的接口成员进行细粒度控制,那么您应该应用interface segregation principle 和接口继承来根据您的需要自定义它们,例如:

interface Isa
{
    void m1();
}

interface Isb
{
    void m3();
}

interface Ia : Isa
{
    void m2();
}

interface Ib : Isb
{
    void m4();
}

class C1 : Isa, Isb
{
   public void m1() { }
   public void m3() { }
}

这样,您就可以准确地实现您想要的并维护接口IaIb 的结构。请记住,这是一个示例,盲目地应用隔离和继承很快就会成为软件设计的反模式。它的使用必须有正当理由并谨慎计划。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-28
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多