Reputation: 57
I'm not sure if this is possible the way I was trying to do it. I might be approaching it wrong, so I'll try to explain the bigger picture a little. I'm pretty new to this sort of programming.
I'm using the NationalInstruments.VISA library to access devices. When you open a connection, the library determines which type of connection it is and loads an interface to match, which gives you access to all of the configuration fields for that connection. The program pulls in an XML file to recall saved connections and their configurations.
In my program, I want to have an array of objects that define all the recalled connection settings so they can be referenced if needed. I'm having trouble figuring out how to define this set of objects though.
This is a generic example of how i'd like to use the objects once they are defined.
public class Device
{
public string type;
}
public class Serial
{
public int baudrate;
public string serialstuff;
}
public class GPIB
{
public int addr;
public string gpibstuff;
public string more stuff;
}
public example()
{
Device[] devlist = new Device[2];
devlist[0]=new Serial();
devlist[1]=new GPIB();
foreach (Device dev in _devlist)
{
if (dev.type == serial) //send serial settings
if (dev.type == gpib) //send gpib settings
}
}
The methods I've tried seem to get me close, but I can't seem to access the fields of the sub-classes without directly declaring the array as that sub-class. I'm probably just approaching this wrong, but I haven't figured out an alternative way.
Upvotes: 1
Views: 47
Reputation: 6522
Device[] devlist = new Device[2];
That line tells you that the variable
devlist
is an array
of type
Device
. Meaning, it can only accept objects
in which is either a direct implementation
or inherits
from Device
.
thus if you consider Serial
and GPIB
as a more specific implementation
of type Device
you can use inheritance
like this
class Serial : Device
class GPIB : Device
or much better, make the Device
an interface
like this
interface IDevice
Upvotes: 0
Reputation: 5735
You are missing some inheritance, for your code to work
public abstract class Device
{
public string type;
}
public class Serial : Device
{
public int baudrate;
public string serialstuff;
}
public class GPIB : Device
{
public int addr;
public string gpibstuff;
public string more stuff;
}
and by type cast to the appropriate concurrent type
if (dev.type == serial)
{
(dev as Serial).baudrate
}
Upvotes: 1