Skip to main content
 首页 » 编程设计

c#之使用接口(interface) C# 时更改

2024年02月23日11me-sa

我有一个接口(interface),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()   
 {...}   
}   

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

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

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

请您参考如下方法:

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

但是,您也可以考虑分离接口(interface),因为拥有一个接口(interface)或基类,其中只有一些方法与一些派生类相关是不明智的。

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