在抽象类的编译时子类实例化一个未知的

时间:2018-02-22 17:46:26

标签: c#

修改

请参阅Amir Popovich的答案解决方案和后续问题(如何通过CTOR参数)

这是我最终代码的内部循环:

//The names of my children classes are the gpib name from *?IDN
//Some start with numbers, thus removing the _ character
if (child.Name.Replace("_","") == gpibInstrument)
{
    var instance = (GpibDevice)Activator.CreateInstance(child, gpibAddr);
    gpibDeviceList.add(instance);
    break;
}

ORIGINAL

我正在试图弄清楚如何在基于某些逻辑集的抽象类的编译时子类中实例化未知。逻辑如下:

  1. 获取连接设备
  2. 根据我看到的设备实例化类
  3. 返回这些类的列表
  4. 我这样做的主要原因是我不需要回到这段代码并添加不同的子类,因为我添加了更多的子类。

    这是我到目前为止的代码:

    //Get IEnumerable of available children class types of my abstract
    //class GpibDevice
    var children = typeof(GpibDevice)
                   .Assembly.GetTypes()
                   .Where(t => t.IsSubclassOf(typeof(GpibDevice)) && !t.IsAbstract);
    
    //Get list of connected equipment
    string[] equipList = GpibUtilites.GetEquipmentNames();
    
    //List which will contain the newly instantiated classes
    List<GpibDevice> gpibDeviceList = new List<GpibDevice>();
    
    foreach (var gpibInstrument in equipList)
    {
        foreach (var child in children)
        {
            if(child.Identifier == gpibInstrument)
            {
                //////INSTATIATE HERE//////
                gpibDeviceList.add(instantiatedClass);
            }
        }
    }
    return gpibDeviceList;
    

    谢谢!

1 个答案:

答案 0 :(得分:1)

使用Activator.CreateInstance并投射到您的抽象类:

if(child.Identifier == gpibInstrument)
{
    //////INSTATIATE HERE//////
    var instance = (AbstractClassType)Activator.CreateInstance(child);
    gpibDeviceList.add(instantiatedClass);
}

如果你知道你的类在其CTOR中有参​​数,你可以将其作为对象传递[]:

var @params = new object[]{p1,p2...pn};
var instance = (AbstractClassType)Activator.CreateInstance(child, @params);