在创建部分关系时使用嵌套类型(而不是使用该类类型的变量/字段数据)有什么好处(示例引擎是汽车的一部分) 换句话说,以下内容之间有什么区别: (1)
public class Engine
{
//some attributes like engine type and constructor
. . .
}
public class Car
{
Engine e;
Public Car(string type)
{
e = new Engine(type);
}
.......
}
和
(2)
public class Car
{
public class Engine
{
. . .
}
}
然后你可以做类似的事情
Car.Engine e;
e = new Car.Engine();
e.type = something;
最佳答案
我会说嵌套类型的使用是为了组织和特殊性。像您的示例中的嵌套类的问题是 Engine
是所有类型车辆的必要对象,因此将它嵌套在特定车辆中没有多大意义。
你可以说也许使用命名空间会更好;毕竟,如果将 Engine
类放在 namespace CarsAreCool.Car
中,您仍然可以通过 Car.Engine
引用该对象,但是实际上与 Car
类上的 Engine
类型的公开属性没有什么不同。
所以这是我认为它有用的地方:
假设我们有一个接口(interface) IVehicle
,我们所有的车辆都实现了它,以及与车辆相关的其他通用类。
public interface IVehicle
{
public Engine Engine;
public int PassengerCapacity;
public int NumberOfWheels;
}
Car
、Truck
、Van
、Motorcycle
等都会实现这一点,因为它是一种车辆.现在以 Motorcycle
类为例。 Helm 是摩托车特有的东西,它们本身有一些属性,所以拥有属性 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
}
关于c# - 为什么在创建部分关系(组合)时使用嵌套类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35117476/