Allow installation of only a specific class / instance

Imagine that I have two classes A and B, where B has the properties BProperty1 and BProperty2.

  • The BProperty1 property should only be set by class A (no matter which instance)
  • The BProperty2 property should be set only by a specific instance of class A (a link to this instance can, for example, be stored in BProperty1).

Is it possible to implement something like this, maybe a template for this? Note that A and B are independent, none of them are the result of the other! I am using C # and WPF. Thanks for any hint!

EDIT Example:

Imagine a Car class and a CarDoor class. Whenever a CarDoor is added to a car, the CarDoors AssociatedCar property is set to the Auto to which it is assigned because this link is needed later. But how to make sure that the AssociatedCar property is not set by the user, but by the Car class, when the AddCarDoor (door) is called?

class Car
{
    private List<CarDoor> _carDoors = new List<CarDoor>();

    public Car()
    {

    }

    public void AddCarDoor(CarDoor door)
    {
        // Add the door to the car
        _carDoors.Add(door);

        // Save a reference to the car assigned to the door
        door.AssociatedCar = this;
    }
}


class CarDoor
{
    public Car AssociatedCar;

    public CarDoor()
    {

    }
}
+3
source share
4 answers

You can lock the setter and then make the object mandatory to close it for class A.

: , , , . , , . - . .

Edit2: , ( , ) . , - , .

...

Class Car
{
    private List<CarDoor> carDoors;

    Car()
    {
         this.carDoors = new List<CarDoor>();
    }

    public List<CarDoor> getCarDoors
    {
         return this.carDoors;
    }
}
+1

, :

class CarFactory
{
    public Car BuildCar()
    {
        return new Car(BuildDoor);
    }

    public CarDoor BuildDoor(Car car)
    {
        return new CarDoor(car);
    }
}

class Car
{
    private List<CarDoor> _carDoors = new List<CarDoor>();

    public Car(Func<Car, CarDoor> buildDoor)
    {
        for (int i=0; i<4; i++)
            _carDoors.Add(buildDoor(this));
    }
}


class CarDoor
{
    private Car _associatedCar;

    public CarDoor(Car associatedCar)
    {
        _associatedCar = associatedCar;
    }
}

, , . , CarDoor , . , , , , , , , Mechanic.

+1

//dll . , , , , .

+1

, System.Diagnostics.StackTrace class) . , setter, , , A.

:

  • .
  • , - , , , - . , , , .
0

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


All Articles