【问题标题】:change when use interface C#使用接口 C# 时更改
【发布时间】:2011-10-05 06:27:39
【问题描述】:

我有一个接口,2类

public interface ITest  
{  
 void Method1(){}  
 void Method2(){}   
}  
public class Test1 : ITest  
{  
 //Just implement Method1() (how can I just implement Method1() without implementing Method2()?)
 public string Method1()  
 {...}  
}  
public class Test2 : ITest  
{  
 //Implement both Method1() & Method2()
 public string Method1()  
 {...}  
}  

对于请求,我必须在接口中添加更多名为 Method3() 的方法,我的接口应该是:

public interface ITest  
{  
 void Method1(){}  
 void Method2(){}    
 void Method3(){}   
}  

我必须将 Method3() 添加到类 Test1 和 Test2 中,我可以在需要时添加。
非常感谢

【问题讨论】:

标签: c# interface


【解决方案1】:

您应该使用抽象基类而不是接口,并将方法设为虚拟。在您的派生类中,您应该只能覆盖那些有意义的类。

但是,您也可以考虑分离接口,因为只有某些方法与某些派生类相关的接口或基类是不明智的。

您可以选择在未实现的方法中抛出异常,但这应该是最后的手段。

【讨论】:

  • 如果方法没有意义,接口可能做的太多了。您可能希望将界面一分为二。
【解决方案2】:

我想说,如果你不实现所有方法,那么你的类就不是ITest 类型。我会写你的代码如下:

public interface ITest1
{
    void Method1();
}
public class interface ITest2 : ITest1
{
    void Method2();
}
public class Test1 : ITest1
{
    public void Method1() {}
} 
public class Test2 : ITest2
{
    public void Method1() {}
    public void Method2() {}
} 

【讨论】:

    【解决方案3】:

    接口必须由其类完全实现。

    但是,您可以做的是创建一个新接口,其名称可以更好地表达它的本质,而 Method3 的另一个名称可以更好地表达其意图。

    然后让应该公开此功能的类实现新接口。

    public interface IDescriptionOfWhatIAm
    {
        void MethodNameWithGoodDescription();
    }
    
    public class Test1 : IDescriptionOfWhatIAm
    {
        public void MethodNameWithGoodDescription() {}
    }
    

    详细了解interface segregation principle 和 SOLID 原则。

    【讨论】:

      【解决方案4】:

      您必须实现方法 2,但您可以显式地实现它。不过有点丑。

      public interface ITest  
      {  
       void Method1(){}  
       void Method2(){}   
      }  
      public class Test1 : ITest  
      {  
       //Just implement Method1() (how can I just implement Method1() without implementing             Method2()?)
       public string Method1()  
       {...}
      
          private void ITest.Method2(){ throw new NotSupportedException(); }    
      }  
      public class Test2 : ITest  
      {  
       //Implement both Method1() & Method2()
       public string Method1()  
       {...}  
      }  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-29
        相关资源
        最近更新 更多