【问题标题】:C# Accessing Higher-Level Method from Nested ClassC# 从嵌套类访问高级方法
【发布时间】: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()。有没有办法做到这一点?

谢谢!

【问题讨论】:

标签: c# nested-class


【解决方案1】:

嵌套类不会“看到”其宿主中声明的任何内容。

您应该将宿主引用传递给任何嵌套类,例如,在构造函数中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多