如何从构造函数中给出的另一个实例访问方法?

时间:2015-01-28 22:48:34

标签: c# oop

所以我有以下设置。

检测控制室温度的传感器然后检查它是否低于或高于设定温度,如果低于或高于它,则启动加热器。 现在我如何让方法GetCurTemp()获得我设定的温度?

public class TempSensor
{
    public int Temp { get; set; }
}
public class Control
{
    private int threshold;
    public Control(TempSensor t, Heater h, int thr)
    {
      threshold = thr;
    }
    public void SetThreshold(int thr)
    {
        threshold = thr;
    }
    public int GetThreshold()
    {
        return threshold;
    }
    public int GetCurTemp()
    {
        return ???;
    }
}
class Test
{
    static void Main(string[] args)
    {
        var tempSensor = new TempSensor();
        var heater = new Heater();
        var uut = new Control(tempSensor, heater, 25);
        Console.WriteLine("Set the current temperatur");
        int n= int.Parse(Console.ReadLine());
        tempSensor.Temp = n;
    }
}

2 个答案:

答案 0 :(得分:1)

您需要在TempSensor课程中保留对Control的引用。然后,您可以从该参考中访问温度。

public class Control
{
    private int threshold;
    private TempSensor sensor;

    public Control(TempSensor t, Heater h, int thr)
    {
      threshold = thr;
      sensor = t;
    }

    public void SetThreshold(int thr)
    {
        threshold = thr;
    }

    public int GetThreshold()
    {
        return threshold;
    }

    public int GetCurTemp()
    {
        return sensor.Temp;
    }
}

答案 1 :(得分:0)

您没有对您传递到TempSensor构造函数的Control对象做任何事情。您应该在sensorTemp类中设置Control这样的字段来保存此值。

public class Control
{
    private int threshold;
    private int sensorTemp;

    public Control(TempSensor t, Heater h, int thr)
    {
      threshold = thr;
      sensorTemp = t.Temp;
    }

    public void SetThreshold(int thr)
    {
        threshold = thr;
    }

    public int GetThreshold()
    {
        return threshold;
    }

    public int GetCurTemp()
    {

        return sensorTemp;
    }


}