【发布时间】:2011-09-21 14:44:05
【问题描述】:
我想为通过串行端口通信的外部控制电路创建一个库类。该电路内置了使用串行通信获取/设置各种设置的功能(例如,发送“SR,HC,01,1,\r”打开传感器 1)。有大约 100 种功能分为以下几类:传感器设置、输出设置和环境设置。这是我尝试过的。
public class CircuitController
{
// Fields.
private SerialPort controllerSerialPort;
private SensorSettings sensorSettings;
private OutputSettings outputSettings;
private EnvironmentSettings environmentSettings;
...
// Properties.
// Properties to get sensorSettings, outputSettings, and environmentSettings.
// Methods.
public string SendReceive(string sendCommand) // Send command and receive response.
{
...
}
// Nested classes.
public class SensorSettings
{
// Fields.
// The various sensor settings here.
// Properties.
// Properties to get/set the sensor settings. Note: Get/Set is done through calling one of the following methods.
// Methods.
public double GetSensorUnits(int sensorNumber)
{
...
string commandToSend = String.Format("HE,WL,1,{0}", sensorNumber); // Setup command string.
string commandResponse = SendReceive(commandToSend); // Send command and receive response. ERROR here, cannot access higher level, non-static methods.
// Logic to process commandResponse.
...
}
// Other methods to create, send, and process the circuit's sensor settings "functions".
}
public class OutputSettings
{
// Same logic as SensorSettings class.
}
public class EnvironmentSettings
{
// Same logic as SensorSettings class.
}
}
我认为这样CircuitController 类下不会有 100 个方法/属性。例如,我可以使用 get 属性来获取 sensorSettings 实例,然后调用所需的方法/属性:circuitControllerInstance.GetSensorSettingsProperty.GetSensorUnits(1);。我收到一个编译错误,我试图从嵌套类访问SendReceive()。有没有办法做到这一点?
谢谢!
【问题讨论】:
-
如果您有兴趣,Microsoft 的类库开发设计指南提供了避免公共嵌套类型的一般建议:msdn.microsoft.com/en-us/library/ms229027.aspx
-
有完整源代码示例工作的最终解决方案吗?
标签: c# nested-class