How to make a nested class that can access members of the class that created it?

Im programming in C # .NET. I want to create a nested class that can access the members of the instance that created it, but I cannot figure out how to do this.

This is what I want to do:

Car x = new Car()
x.color = "red";
x.Door frontDoor = new x.Door();
MessageBox.Show(frontDoor.GetColor());    // So I want the method GetColor of the class Front Door to be able to access the color field/property of the Car instance that created it.

How should I do it? I tried to nest the Door class inside the Car class, but it cannot access the members of the Car class this way. Do I need to get a car to inherit a door class or something else?

+3
source share
6 answers

The easiest way is to return the Doorlink to the Carone that created it.

For instance:

class Car { 
  public string color;
  public Door Door() { return new Door(this); }
  class Door { 
    Car owner;
    Door(Car owner) { this.owner = owner; }
    string GetColor() { return owner.color; }
  }
}
+5

, .

CAR, CAR. CAR DOOR , setter DOOR.

+2

, - . - "". . , , , , = (this.Colour); 'this' . , , . , , , , .

+2

, Door, Car. # ( - ), , , .

: Door, Car as. private readonly. GetColor() , color Car.

GetColor() get -only Car Door. ( , ), .

+1

Car , , Car Door, Composition

:

public class Car
    {
        public string Color;
    }

    public class Door
    {
        public string T;

        public Car C;
    }

. , Car Door.

0

Door , Car GetColor() :

public class Car
{
    private class Door
    {
        public Door(Func<Color> getColourFunc)
        {
        }
    }
}
0

Source: https://habr.com/ru/post/1733434/


All Articles