使用C#接口时改变
我有一个接口,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 和 Test1 中吗? Test2,我需要的时候就可以添加吗
非常感谢
I have an interface, 2 class
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()
{...}
}
For the request, I must add more method called Method3() to the interface, my interface should be:
public interface ITest
{
void Method1(){}
void Method2(){}
void Method3(){}
}
Must I add Method3() to both class Test1 & Test2, can I just add when I need.
Many Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该使用抽象基类而不是接口,并将方法设置为虚拟方法。在派生类中,您应该只能覆盖那些有意义的类。
但是,您也可以考虑分离接口,因为拥有一个仅某些方法与某些派生类相关的接口或基类是不明智的。
您可以选择在未实现的方法中引发异常,但这应该是最后的手段。
You should be using abstract base class instead of an interface and make the methods as virtual. In your derived classes you should be able to override only those that make sense.
However you can also consider separating the interfaces since its not wise to have an interface or a base class of which only some methods are relevant to some derived classes.
You can chose to throw exceptions in unimplemented methods but that should be the last resort.
我想说的是,如果您没有实现所有方法,那么您的类就不是
ITest
类型。我会按如下方式编写您的代码:I would say that if you don't implement all methods then your class is not of type
ITest
. I would write your code as follows:接口必须由其类完全实现。
但是,您可以做的是创建一个新接口,其名称可以更好地表达其含义,而 Method3 则可以使用另一个名称,以更好地表达其意图。
然后让应该公开此功能的类实现新接口。
详细了解接口隔离原则和 SOLID 原则。
An interface must be fully implemented by its classes.
However, what you can do is to create a new interface with a name that better expresses what it is, with the Method3 with another name that better expresses its intent.
And then have the classes that should expose this functionality implement the new interface.
Read more about the interface segregation principle and SOLID principles.
您必须实现方法 2,但您可以显式实现它。不过它有点丑。
You have to implement Method 2, but you can implement it explicitly. However its a little ugly.