限制子类继承基类的某些方法
using System;
public class Base
{
public Base()
{
}
public void M1()
{
}
public void M2()
{
}
public void M3()
{
}
}
public class Derived : Base
{
//this class should get only method 1
}
public class SecondDerived : Base
{
//this class should get only method 2 and method3
}
要求是:基类包含 3 个方法 M1
、M2
、M3
。
派生类应仅继承 M1
,SecondDerived 应仅继承 M2
和 M3
。
这怎么能做到呢?
using System;
public class Base
{
public Base()
{
}
public void M1()
{
}
public void M2()
{
}
public void M3()
{
}
}
public class Derived : Base
{
//this class should get only method 1
}
public class SecondDerived : Base
{
//this class should get only method 2 and method3
}
The requirement is : the base class contains the 3 methods M1
, M2
, M3
.
The derived class should inherit only M1
and SecondDerived should inherit only M2
and M3
.
How can this be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可以通过添加 Obsolete 属性来实现
It is possible by adding Obsolete attribute
您不能有选择地继承这样的方法。派生类自动继承基类的所有公共方法。我建议您将
Base
类拆分为两个类:You cannot selectively inherit methods like this. A derived class automatically inherits all public methods of the base class. I suggest you to split the
Base
class into two classes:你不能用这种方式来做。继承意味着“IS A”关系。
如果
SecondDerived
没有M1()
那么它将与对class Base
的引用不兼容。因此,也许您不应该使用继承来解决您正在解决的任何问题。
You cannot do it in this way. Inheritance implies an "IS A" relationship.
If
SecondDerived
would not have aM1()
then it would not be compatible with a reference to a theclass Base
.So maybe you shouldn't be using inheritance for whatever problem you're solving.
通过继承不可能做你想做的事。
看来您无意覆盖,您只是想有选择地“继承”基类的行为。您可以使用“有”关系来做到这一点:
然后只需执行以下操作:
更新:一个可能的替代解决方案是使您的
Base
类方法virtual< /code> 并在派生类中重写它们,在您不希望该类提供的那些方法中抛出
NotSupportedException
。我不太喜欢这个解决方案,但它的优点是不会失去多态性继承,如果您有一些所有派生类都将共享的核心基本功能,这可能会很有用(在您的示例中,您似乎暗示它们不会)。It is not possible to do what you want with inheritance.
It seems you have no intention of overriding, you simply want to "inherit" behavior from the base class selectively. You could do this using a "has a" relationship:
Then simply do the following:
UPDATE: A possible alternative solution is to make your
Base
class methodsvirtual
and override them all in your derived classes, throwingNotSupportedException
s in those methods that you do not want the class to make available. I don't really like this solution but it has the advantage of not loosing the polyphormism inheritance gives you which might be useful if you have some core base functionality which all derived classes will share (in your example you seem to imply they wont).