【发布时间】:2015-05-22 10:33:46
【问题描述】:
是否可以在基类中实现接口并允许在第一个派生类级别调用/覆盖已实现的方法,但阻止从任何进一步的派生类调用它?
public interface IInterfaceSample
{
bool Test();
}
public class Base: IInterfaceSample
{
public virtual bool Test()
{
return True;
}
}
public class Sub1: Base
{
//I need to be able to override the Test method here
public override bool Test()
{
return True;
}
}
//Under a separate project:
public class Sub2: Sub1
{
//I need to prevent overriding the interface implementation in this class
}
现在我需要的是:
var b = new Base();
b.Test();//This should work
var s1 = new Sub1();
s1.Test();//I need this to work too
var s2 = new Sub2();
s2.Test();//I need to prevent doing this
到目前为止,我认为这可能是不可能的,因为接口必须是公共的,否则使用它们没有真正的价值。
就我而言,我需要 Sub2 类才能访问 Sub1 中的属性,但只能访问该类的方法,尤其是接口实现方法。
我能够做到这一点的唯一方法是根本不使用接口并这样做:
public class Base
{
internal virtual bool Test()
{
return True;
}
}
public class Sub1: Base
{
//I am able to override the Test method here
internal override bool Test()
{
return True;
}
}
//Under a separate project:
public class Sub2: Sub1
{
//Nothing to override here which is what i need
}
var b = new Base();
b.Test();//This works
var s1 = new Sub1();
s1.Test();//This works too
var s2 = new Sub2();
s2.Test();//This is prevented
但是我想知道这是否仍然可以通过接口实现,非常感谢任何帮助。
【问题讨论】:
-
如果 Sub1 继承了接口,那么 Sub2 不需要继承接口的任何成员,因为它们已经通过 Sub1 继承。顺便说一下,你可以把接口做成内部的。
-
在我看来您需要重新设计您的对象模型,如果子类不应该具有父类的某些功能,那么它应该是子类吗?如果您将
Sub2的实例传递给可以接受Base的任何实例的方法会发生什么? -
我刚试过这个,但是 Sub2 仍然可以覆盖 Test 方法的实现,并且可以从 Sub2 类实例调用 Test 方法,我需要防止这两种情况。
-
好点@TrevorPilley,但是,在我的情况下,将 Sub2 创建为 Sub1 的子项的唯一目的是共享属性结构而不共享其他功能和方法,Sub1 和 Sub2 将用于两个项目的不同端和不同端将在错误的地方访问,我只需要防止在另一个地方复制 Sub 1,只需从中删除方法即可实现我的目标。
标签: c# class interface base derived