C # Make a protected variable confidential in a subclass (or otherwise around the problem)

I do not think it can be done, but I'm curious. Is it possible to make a protected variable in the superclass private in its subclass.

For example, I have three classes SuperClass, SubClass : SuperClassand SubCLass2 : SubClass.

I want to have access to a variable protected string[] commandsthat is in SuperClassfrom SubClass, but denies access to it from SubClass2.

If this is not possible, do you still need to achieve the same effect?

+3
source share
3 answers

I do not think it can be done, but I'm curious. Is it possible to make a protected variable in the superclass private in its subclass.

. - - . , "" ... .

, , :

public class Base
{
    private int foo = 5;
    protected int Foo { get { return foo; } }
}

public class Child : Base
{
    protected new int Foo { get { return 0; } }
}

public class GrandChild : Child
{
    // Aargh, can't get at the original Foo...
}

? , ...

EDIT: , : , ( ), . , .

+7

, ( , Skeet ), - , . , , - .

 interface I
 {
   int Prop { get; set; }
 }

 class A : I
 {
   int I.Prop { get; set; }
 }

 class B : A
 {
   public void Bar()
   {
     (this as I).Prop = 2;
   }
 }

 class C : B
 {
   public void Foo()
   {
     //Prop = 1;
   }
 }
0

I think you can create a container for a variable and share it between SubClass and SuperClass, for example:

class Prop {
    public string Str = "a string";
}
class A {
    Prop prop;
    protected A(Prop p) { prop = p; }
    public A() : this(new Prop()) { }
}
class B : A {
    Prop prop;
    private B(Prop p) : base(p) { prop = p; }
    public B() : this(new Prop()) { }
}
class C : B {
    public void Meth() {
        // has no access to prop.Str
    }
}
0
source

All Articles