所以我有以下设置。
检测控制室温度的传感器然后检查它是否低于或高于设定温度,如果低于或高于它,则启动加热器。
现在我如何让方法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;
}
}
答案 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;
}
}