如何从构造函数中给出的另一个实例访问方法?
How to acces a method from another instance that was given in the constructor?
所以我有以下设置。
检测房间温度的传感器和控制器然后检查它是低于还是高于设定温度,如果低于设定温度则启动加热器。
现在我如何获得方法 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;
}
}
您需要在 Control
class 中保留对 TempSensor
的引用。然后您可以从该参考中访问温度。
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;
}
}
您没有对传递给 Control
构造函数的 TempSensor
对象执行任何操作。您应该在 Control
class 中设置一个像 sensorTemp
这样的字段来保存这个值。
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;
}
}
所以我有以下设置。
检测房间温度的传感器和控制器然后检查它是低于还是高于设定温度,如果低于设定温度则启动加热器。
现在我如何获得方法 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;
}
}
您需要在 Control
class 中保留对 TempSensor
的引用。然后您可以从该参考中访问温度。
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;
}
}
您没有对传递给 Control
构造函数的 TempSensor
对象执行任何操作。您应该在 Control
class 中设置一个像 sensorTemp
这样的字段来保存这个值。
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;
}
}