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#
中使用答案 0 :(得分:0)
I suppose you could write code in class A that checks the calling class name against a white list or a black list and throws an exception in the cases you want to disallow, but I would not recommend doing this. That would be very difficult to maintain, and class A should not need to know about every class that extends it.
What you are trying to do is really honestly a bad idea.
答案 1 :(得分:0)
C# (and .NET in general) has the access modifiers:
public
- Anyone can accessprivate
- Only the containing scope/type can accessprotected
- Only the containing type and its derived types can accessinternal
- Only types defined in the same Assembly (or InternalsVisibleTo
Assemblies) can accessprotected internal
- The set-union of protected
and internal
can access.You're asking for something in-between private
and protected
, where you can manually restrict access to named types.
This is not currently possible to enforce, at least at compile-time, in .NET - though if types A
and B
exist in the same assembly and C
exists in a different assembly then internal
would work.
At runtime you could enforce this with code-access-security, or more simply: using reflection to get the calling-class's name (this.GetType()
), or use a password:
or more simpler: a password requirement:
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
}
}