[英]is this possible in c# ? only one class access base class method and second class can not access the same base class method
A是基类
B衍生自A,C也衍生自A
我只希望B可以访问A,C的方法,而不能访问A的相同方法。
class A {
protected void Foo() {
}
}
class B : A {
void Bar() {
this.Foo(); // OK
}
}
class C : A {
void Baz() {
this.Foo(); // I don't want to permit this
}
}
如何在C#中实现
我认为这看起来像是Interface segregation principle
的问题:
不应强迫客户端依赖于不使用的接口。
但是在您的情况下,可以将其改写为类继承。
创建纯基类(没有要从类C
隐藏的方法)
public class Base
{
protected void SomeDummyMethod()
{
}
}
然后创建A
继承自Base
A
类,并为B
类添加一个共享的方法
public class A : Base
{
protected void YourFooMethod()
{
}
}
创建从A
继承的B
类,并且可以访问所有功能,包括YourFooMethod
public class B : A
{
public void Bar()
{
this.YourFooMethod();
}
}
最后是您的C
类,它具有除YourFooMethod
方法之外的所有基本功能
public class C : Base
{
public void Bar()
{
this.YourFooMethod(); //Compile error: YourFooMethod is not a member of...
}
}
我想您可以在A类中编写代码,该代码对照白名单或黑名单检查调用类的名称,并在您要禁止的情况下引发异常,但我不建议这样做。 这将很难维护,并且A类不需要了解扩展它的每个类。
老实说,您要尝试执行的操作是个坏主意。
C#(通常是.NET)具有访问修饰符:
public
-任何人都可以访问 private
-仅包含作用域/类型可以访问 protected
仅包含类型及其派生类型可以访问 internal
-只有在同一程序集(或InternalsVisibleTo
)中定义的类型可以访问 protected internal
- protected
和internal
可以访问的集合。 您需要在private
和protected
之间,您可以手动限制对命名类型的访问。
当前至少在编译时无法在.NET中强制执行-尽管如果类型A
和B
存在于同一程序集中,而类型C
存在于不同的程序集中,则internal
将起作用。
在运行时,您可以使用代码访问安全性或更简单地实施此操作:使用反射获取调用类的名称( this.GetType()
),或使用密码:
或更简单:密码要求:
class A {
private Boolean isAllowedAccess;
protected A(String password) {
this.isAllowedAccess = password == "12345abc";
}
protected void Foo() {
if( !this.isAllowedAccess ) throw new InvalidOperationException();
}
}
class B : A {
public B() : base("12345abc") {
}
void Bar() {
this.Foo(); // OK
}
}
class C : A {
public C() : base(null) {
}
void Baz() {
this.Foo(); // I don't want to permit this
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.