【问题标题】:Create a third interface that uses the inherit interface implementation c#创建使用继承接口实现c#的第三个接口
【发布时间】:2017-05-22 06:51:26
【问题描述】:

如您所见,我有 2 个接口:

public interface i1
{
 void add(news a);
}

public interface i2
{
void add(file f);
}

这两个接口有自己的实现。我想创建另一个名为 i3 的接口,它继承 i1 和 i2 并使用它们的实现?我该怎么做?

public interface i3:i1,i2
{

}

事实上,我想使用 i2,i1 实现来获取 i3 中的所有方法。因为这些方法的 i3 实现是相同的。

【问题讨论】:

    标签: c# inheritance interface


    【解决方案1】:

    我不明白你的问题,但这编译正确

    public interface I1
    {
        int One { get; set; }
    }
    
    public interface I2
    {
        int Two { get; set; }
    }
    
    public interface I3 : I1, I2
    {
        int Three { get; set; }
    }
    
    // Implementation of I3 (which inherits I1 and I2)
    public class Foo : I3
    {
        public int One { get; set; }
        public int Two { get; set; }
        public int Three { get; set; }
    }
    

    【讨论】:

    • 我不需要上课。我需要第三个界面
    • @EhsanAkbar 你有第三个界面。 I3
    • 你知道我正在使用 wcf 服务。我想将我的所有界面集成到一个界面中,并在 wcf 中定义最终界面
    • @EhsanAkbar 我不确定您关于interface 继承的问题与WCF 有什么关系。快速阅读docs.microsoft.com/en-us/dotnet/articles/csharp/…
    【解决方案2】:

    接口是声明而不是实现。相反,您应该在 i3 中声明您想要的任何内容并在类中继承所有接口

    public interface i1
    {
      int Add(int num1, num2);
    }
    
    public interface i2
    {
     int Multiply(int num1, num2);
    }
    
    public interface i3
    {
     int Divide(int num1, num2);
    }
    
    public class Mathematics: i1, i2, i3
    {
      public int Add(int num1, int num2)
     {
       //Your implementation
     } 
     public int Multiply(int num1, int num2)
     {
       //Your implementation
     } 
    
     public int Divide(int num1, int num2)
     {
       //Your implementation
     }  
    }
    

    如果通过接口本身继承接口的意图类似于

    ICollection<T>

    接口你可以像类继承接口一样继承吗?

    public interface i1
    {
      int Add(int num1, int num2);
    }
    
    public interface i2 
    {
     int Multiply(int num1, num2);
    }
    
    public interface i3 : i1, i2
    {
      int Divide(int num1, int num2);
    }
    
    public class Mathematics:  i3
    {
      public int Add(int num1, int num2)
     {
       //Your implementation
     } 
     public int Multiply(int num1, int num2)
     {
       //Your implementation
     } 
    
     public int Divide(int num1, int num2)
     {
       //Your implementation
     }  
    }
    

    因此,当您在类中继承 i3 时,您将获得您在 i1、i2 和 i3 中声明的所有内容。虽然继承 i1 将只为 i2 提供 i1 成员。

    【讨论】:

    • 我不需要上课。我需要第三个界面
    猜你喜欢
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 2016-10-23
    • 2011-02-17
    • 1970-01-01
    • 2016-09-12
    • 2023-03-13
    相关资源
    最近更新 更多