2016-05-12 127 views
1

我不知道这是可能的,我试图做到这一点。我可能会错误地接近它,所以我会试着稍微解释一下大局。我对这种编程很新颖。嵌套类型和访问字段

我正在使用NationalInstruments.VISA库来访问设备。当您打开一个连接时,库确定它是哪种类型的连接,并加载一个匹配的接口,从而使您可以访问该连接的所有配置字段。该程序将引入一个XML文件以调用已保存的连接及其配置。

在我的程序中,我想要一个定义所有召回连接设置的对象数组,以便在需要时可以引用它们。 我无法弄清楚如何定义这组对象。

这是一个通用的例子,我想如何使用对象,一旦他们被定义。

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 
    } 
} 

我已经试过的方法似乎让我接近,但我似乎无法访问子类的字段,而无需直接声明数组作为该子类。我可能刚刚接近这个错误,但我还没有找到一种替代方法。

+0

[Java在C#中的内部类](http://stackoverflow.com/questions/2367015/java-inner-classes-in-c-sharp)可能会解释你有问题(我不完全确定你是什么有问题,因为你所显示的代码似乎是合理的) –

回答

1

你缺少一些继承,为您的代码工作

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; 
} 

和类型转换为相应的并发类型

if (dev.type == serial) 
{ 
    (dev as Serial).baudrate 
} 
+0

啊!这是我需要的。我的代码中有继承的东西,但我错过了类型转换。一旦我把它放进去,我就能够到达所有的领域。谢谢! – nosjojo

0

Device[] devlist = new Device[2];

这行告诉你,variabledevlistarraytypeDevice。意思是说,它只能接受objects,其中可以是Device的直接implementationinherits

因此,如果您考虑SerialGPIB类型的更具体的implementationDevice可以使用inheritance这样

class Serial : Device

class GPIB : Device

或更好,使Deviceinterface这样

interface IDevice