gpt4 book ai didi

c# 公共(public)嵌套类还是更好的选择?

转载 作者:可可西里 更新时间:2023-11-01 07:49:40 24 4
gpt4 key购买 nike

我有一个控制电路,它有多个设置,并且可以连接任意数量的传感器(每个传感器都有自己的一组设置)。这些传感器只能与控制电路一起使用。我想像这样使用嵌套类:

public class ControlCircuitLib
{
// Fields.
private Settings controllerSettings;
private List<Sensor> attachedSensors;

// Properties.
public Settings ControllerSettings
{ get { return this.controllerSettings; } }

public List<Sensor> AttachedSensors
{ get { return this.attachedSensors; } }

// Constructors, methods, etc.
...

// Nested classes.
public class Settings
{
// Fields.
private ControlCircuitLib controllerCircuit;
private SerialPort controllerSerialPort;
private int activeOutputs;
... (many, many more settings)

// Properties.
public int ActiveOutputs
{ get { return this.activeOutputs; } }
... (the other Get properties for the settings)

// Methods.
... (method to set the circuit properties though serial port)
}

public class Sensor
{
// Enumerations.
public enum MeasurementTypes { Displacement, Velocity, Acceleration };

// Fields.
private ControlCircuitLib controllerCircuit;
private string sensorName;
private MeasurementTypes measurementType;
private double requiredInputVoltage;
... (many, many more settings)

// Properties.
public string SensorName {...}
... (Get properties)

// Methods.
... (methods to set the sensor settings while attached to the control circuit)
}
}

我读到公共(public)嵌套类是“禁忌”,但也有异常(exception)。这个结构可以吗还是有更好的选择?

谢谢!

编辑

下面是我试图为其编写库类的控制电路的粗略层次结构;我使用代码格式来防止文本换行。

Control Circuit (com. via serial port) -> Attached Sensors (up to 10) -> Sensor Settings (approx. 10 settings per sensor)
Basic Controller Settings (approx. 20 settings)
Output Settings (approx. 30 settings)
Common Settings (approx. 30 settings)
Environment Settings (approx. 10 settings)

所有设置都是通过 Controller 设置的,但我想要一个有组织的库,而不是将所有 ~100 种方法、属性和设置塞进一个 Controller 类中。如果有人能提供一个简短的例子来概述他们将使用的结构,我们将不胜感激。谢谢!

最佳答案

类的内容应该是该实现细节。嵌套类是外部类的实现细节,还是您只是将外部类用作方便的名称范围和发现机制

如果是前者,那么您不应该公开私有(private)实现细节。如果它们是类的实现细节,则将它们设为私有(private)。

如果是后者,那么您应该使用命名空间而不是外部类作为范围界定和发现机制。

无论哪种方式,公共(public)嵌套类都是难闻的代码味道。我希望有充分的理由公开嵌套类。

关于c# 公共(public)嵌套类还是更好的选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7984529/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com