可能重複:
C# Inheritance: Static vs. Non-Static FieldC#繼承:使用靜態字段?
我對控制電路產生一個類庫工作:
private abstract class ControllerBasics
{
protected SerialPort serial; // The serial port to communicate with the controller.
protected Dictionary<int, string> errorDescriptions = new Dictionary<int, string> {{1, "Sensor Error"},{2, "Controller Error"}, ...}; // Possible errors for the controller (known and fixed). Won't change from controller to controller.
public string SendReceiveCommand(string command){...} // Method to send string command over "serial".
}
public class OverallController : ControllerBasics // The actual class used to communicate with the controller.
{
// Add top-level controller settings.
private string controllerName = "Controller1"; // Have a property to get/set.
private bool controllerON; // Controller on/off. Have property to get/set.
... // Other similar fields and methods.
// Used to "sort" the controller's many settings/functions.
private SensorSettings sensorSettings; // Have get/set properties for these so I could do the following: overallControllerInstance.GetSensorSettingsProperty.SetActiveSensorCount(5);
private OutputSettings outputSettings;
private EnvironmentSettings environmentSettings;
public OverallController(string name, string comPort, ...) // Constructor.
{
// Basic settings initialization.
// Create serial port.
this.sensorSettings = new SensorSettings(this.serial);
this.outputSettings = ...
}
public class SensorSettings : ControllerBasics // Class to hold the controller's specific sensor settings and their respective get/set methods. Not a new type of controller.
{
private int activeSensorCount; // Have public method to get/set.
... // Others.
public void SetActiveSensorCount(int sensorCount)
{
// Send command using inherited SendReceive().
}
... // Others.
}
public class OutputSettings : ControllerBasics // Same logic as SensorSettings.
{
private string units; // Have public method to get/set.
... // Others.
public string GetUnitType() // Meters, mm, um...
{
// Send command using inherited SendReceive().
}
... // Others.
}
public class EnvironmentSettings : ControllerBasics // Same logic as SensorSettings.
{
...
}
所以,如果errorDescriptions
在ControllerBasics
定義是已知的和固定的在編譯時我應該將其設爲靜態的,還是應該讓它保護,並且每個派生類都會保留有它自己的字典(即this.errorDescriptions)?如果我將其設爲靜態,我將如何在派生類中引用它?例如,如果在Sensor Settings
中我會使用ControllerBasics.errorDescriptions
或SensorSettings.errorDescriptions
?
謝謝!
如果你看看大多數新問題,他們很可能是前一個問題的重演。人們通常在發佈之前不會搜索他們的問題。 –