Im a bit new to the finer points of OOP (inheritance, etc) so please excuse (and feel free to correct ) any terminology errors.
I have a number of different sensors all of which have certain common properties such as ipaddress, port and description, and different methods to read or calibrate.
Obviously I can create individual classes for each sensor type but that would mean writing the same code to read and write properties, therefore there is a class SensorBase that each sensor (SensorA, SensorB & SensorC extend) .
The base class is as follows:
public class SensorBase
{
private int portNo;
private string iP;
private string description;
public int PortNo
{
get
{
return portNo;
}
set
{
portNo = value;
}
}
public string IP
{
get
{
return iP;
}
set
{
iP = value;
}
}
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
A typical sensor class is as follows:
public class SensorB : SensorBase
{
public int Read()
{
//real code would read sensor of type B
return System.DateTime.Now.Minute
;
}
public int Connect()
{
return 0;
}
}
So now I can instansiate an object MySensorB and have IPAddress, Port, Description and a Read method. So far so good.
What I really want is a collection of different sensors with a method to read all the sensors. So I need to guarantee that all Sensors that might be added to the collection have certain properties and methods I believe I need to implement an interface. So I add the following
public interface ISensors
{
int Read();
int Connect();
string Description();
}
and change my Sensor code to:
public class SensorB : SensorBase,ISensors
{
public int Read()
{
return System.DateTime.Now.Minute
;
}
public int Connect()
{
return 0;
}
}
Now if I do not implement either Read or Connect I get a compile error. Again just what I want.
I create my collection:
public class SensorCollection:Collectio
nBase
{
public virtual void Add(ISensors Item)
{
this.List.Add(Item);
}
public void ReadAll()
{
foreach (ISensors Sensor in this.List)
{
int Value=Sensor.Read();
Console.WriteLine ("Read Value {0} From Sensor {1}", Value, Sensor.Description);
}
}
}
This is where the problem starts I can leave Description in my Interface whereupon I have to implement Description in each Sensor (the project is OK, but I have identical code in each sensor class which seems kind of wrong).
If I comment out Description from the interface, I cannot access Sensor.Description in the ReadAll method as the object Sensor is of type Isensors (even though all the objects in the collection will be SensorA, SensorB and SensorC and will have a Description that is defined in SensorBase).
Is there a way that each different sensor can inherit from SensorBase and the inherited properties, methods and events can be used in my collection?