7
Answers

Accessing subclass properties in a List

Pi Robot

Pi Robot

14y
6.2k
1
I have written a C# program that controls a robot.  I have a Sensor class that defines common properties among different types of sensors, but then I have individual sub-classes for sensors with specific properties.  My problem is that I want to define my robot as having a list of sensors (List<Sensor>) but I want to be able to access the special properties of sub-classed sensors if they are in the list.  Here is some specific code.  First, the Sensor class:

public abstract class Sensor : Node
    {
        private PropertyClass _Properties;

        public new class PropertyClass : Node.PropertyClass
        {
            public int Value;
            public int UpdateInterval;
            public SensorType Type;
            public SensorModel Model;
        }

        public new PropertyClass Properties
        {
            get { return _Properties; }
            set { _Properties = value; }
        }

        public enum SensorType
        {
            IR,
            Sonar,
            Touch,
            Light,
            PIR
        }

        public enum SensorModel
        {
            Sharp_GP2D12,
            Ping_Sonar
        }

        public Sensor(string Name) : base(Name)
        {
            _Properties = new PropertyClass();
        }
    }

Now a subclass for an IR Sensor:

public class IR : Sensor
    {
        private PropertyClass _Properties;

        public new class PropertyClass : Sensor.PropertyClass
        {
            public int MinRange;
            public int MaxRange;
        }

        public new PropertyClass Properties
        {
            get { return _Properties; }
            set { _Properties = value; }
        }

        public IR(string Name)
            : base(Name)
        {
            _Properties = new PropertyClass();
            this.Properties.Type = Sensor.SensorType.IR;     
        }

If I define a list of sensors like this:

List<Sensor> mySensors = new List<Sensor>();

And then I add an IR sensor:

mySensors.Add(new IR("My IR Sensor"));

Then I cannot get access to the MinRange and MaxRange properties of the sensor.  For example, mySensors[0].MinRange is not defined because the compiler thinks mySensors[0] is just a generic Sensor type and doesn't know that it is the IR sub-type.

Is there a way I can make this work?

Thanks!



Answers (7)