是否可以在基类中实现接口并允许在第一个派生类级别调用/覆盖已实现的方法,但阻止从任何进一步的派生类调用它?
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
但是我想知道这是否仍然可以通过接口来实现,非常感谢任何帮助。
不,这是不可能的——它会破坏多态性的全部意义。特别是,假设您没有使用var
,但明确使用了类型:
Sub1 s2 = new Sub2();
s2.Test();
必须编译:
- 第一行必须编译,因为
Sub2
源自Sub1
.
- 第二行必须编译,因为你想要
s1.Test()
进行编译,其中编译时类型s1
is Sub1
以及。
根据经验,如果您有两个类 X 和 Y,并且只有someX 上的公共操作对 Y 有效,那么 Y 不应该从 X 派生。您应该能够将派生类的任何实例视为基类(及其实现的所有接口)的实例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)