Why use nested types when creating a partial dependency (composition)

What is the advantage of using the Nested type (instead of using variables / data fields of this class type) when creating a partial relation (the example engine is part of Car) In other words, what is the difference between the following: (1)

public class Engine
{
//some attributes like engine type and constructor
 . . . 
}
public class Car
{
    Engine e;
    Public Car(string type)
      {
          e = new Engine(type);
      }
    .......
}

AND

(2)

public class Car
{
   public class Engine
    {
       . . . 
    }
}

and then you can do something like

Car.Engine e;
e = new Car.Engine();
e.type = something;
+4
source share
2 answers

, . , , , Engine , .

, , , ; , Engine namespace CarsAreCool.Car, Car.Engine, Engine Car.

, , :

, IVehicle, , , .

public interface IVehicle 
{
    public Engine Engine;
    public int PassengerCapacity;
    public int NumberOfWheels;
}

Car, Truck, Van, Motorcycle .. , . Motorcycle. - , , , HelmetColor, HelmetSize, HelmetVisorType off Motorcycle ? , Helmet. , , , , .

public class Motorcycle : IVehicle
{
    #region IVehicle implementation 

    #endregion

    #region Nested Types

    public sealed class Helmet
    {
        public string Color;
        public string Size;
        public string VisorType;
        public bool RequiredByLaw;
    }

    public Helmet Helmet;
    public decimal Mileage;

    #endregion
}
+1

, , , . . : , . , , . Turbo . Turbo. .

public class Car
{ 
     public Engine Engine;
     public List<Tire> Tires;
}
public class Engine
{
     public string Type;
     public string Cylinder;
     public class Turbo
     {
          public string Name;
          public string Power;
          public void CalculatePower()
          {
          }
     }
}
public class Tire
{
}
0

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


All Articles