Frage

Hier ist mein aktuelles Layout: (die Frage ist der Kommentar)

class A
{  
    int foo;  
}

class B : A {}

class C : B
{
    void bar()
    {
        //I want to access foo
        base.foo; // Doesn't work
        base.base.foo // Doesn't work, of course
    }
}

Wie Sie sehen können, habe ich nicht Mitglieder A unter Verwendung base in C zugreifen Wie könnte ich darauf zugreifen? Danke:)

War es hilfreich?

Lösung

Wenn Sie machen foo geschützt,

class A
{  
    protected int foo;  
}

dann eine einfache Basis tun:

  void bar()
  {
        //I want to access foo
        base.foo; // will work now
        // base.base.foo // Doesn't work, of course
  }

Aber es wäre besser, eine (geschützte) Immobilie um foo zu erstellen:

   class A
   {  
        private int _foo;  
        protected int Foo 
        {
           get { return _foo; }
           set { _foo = value; }
        }
   }

Andere Tipps

Das Feld in A private deklariert. Es sollte für abgeleitete Klassen geschützt werden, darauf zuzugreifen.

öffentliche Stellen Sie vor int foo;

class A
{  
    public int foo;  
}

class B : A {}

class C : B
{
    void bar()
    {
        //I want to access foo
        base.foo; // Now you can see it
    }
}

In der Standardeinstellung, wenn Sie angeben, sonst alle Mitglieder privat sind.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top