0
我想爲通過串口進行通信的外部控制電路創建類庫。該電路內置了使用串行通信(例如發送「SR,HC,01,1,\ r」打開傳感器1)來獲取/設置各種設置的功能。有大約100個功能分爲以下類別:傳感器設置,輸出設置和環境設置。這是我試過的。C#從嵌套類訪問高級方法
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.
}
}
我計算過,這樣就不會有100種方法/ CircuitController
類下擠滿屬性。例如,我可以使用get屬性來獲取sensorSettings實例,然後調用所需的方法/屬性:circuitControllerInstance.GetSensorSettingsProperty.GetSensorUnits(1);
。我收到一個編譯錯誤,我試圖從嵌套類訪問SendReceive()
。有沒有辦法做到這一點?
謝謝!
如果您有興趣,Microsoft開發類庫的設計指南提供了避免公共嵌套類型的一般建議:http://msdn.microsoft.com/en-us/library/ms229027.aspx –
任何最終解決方案完整的源代碼示例工作? – Kiquenet