这可能在c#中?只有一个类访问基类方法和第二个类不能访问相同的基类方法

时间:2016-08-13 13:22:35

标签: c#

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#

中使用

2 个答案:

答案 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 access
  • private - Only the containing scope/type can access
  • protected - Only the containing type and its derived types can access
  • internal - Only types defined in the same Assembly (or InternalsVisibleTo Assemblies) can access
  • protected 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
    }
}