如何将Type对象用作具体类型?

时间:2019-04-13 17:03:33

标签: c# types

我正在使用一个外部C#库,该库在其过程中使用了泛型。但是我想在外部类的循环中使用它。我的问题是我无法在类之间传递类型。

这里是一个例子:

我使用SettingsXmlReader类读取xml文件的某些部分。这些部分在具体的类中指定:

SettingsXmlReader settingsXmlReader = new SettingsXmlReader(settingsXmlPath);
settingsXmlReader.AddContainer(typeof(ReleasePathContainer));
settingsXmlReader.AddContainer(typeof(HistoryPathContainer));
(...)

所以我将我的具体类型传递给settingsXmlReader对象,但是现在,我不能像下面的方法那样使用这些类型(因为外部库需要它):

foreach (Type aContainer in containers)
{
    XmlContainerInitializer<aContainer> containerInitializer = new XmlContainerInitializer<aContainer>();
    IBaseContainer container = containerInitializer.InitializeXmlContainer(settingsXmlFile);
}
'aContainer' is a variable but is used like a type

我也尝试了以下模式:

SettingsXmlReader settingsXmlReader = new SettingsXmlReader(settingsXmlPath);
settingsXmlReader.AddContainer<ReleasePathContainer>();
settingsXmlReader.AddContainer<HistoryPathContainer>();

但是在这种情况下,我不知道如何存储或使用它:

private IList<T> containers;
public void AddContainer<T>()
{
    containers.Add<T>();
}

1 个答案:

答案 0 :(得分:0)

如果您确实需要使用“ aContainer”循环,则可以使用MakeGenericType来避免变量vs类型错误,如下所示:

Type[] typeArgs = new Type[] { aContainer };

Type genericType = typeof(XmlContainerInitializer<>);
Type specificType = genericListType.MakeGenericType(typeArgs);

// This gets you a XmlContainerInitializer of the right type
var containerInitializer = Activator.CreateInstance(specificType);

// You can then try using it dynamically
dynamic d = containerInitalizer;
IBaseContainer container = (IBaseContainer)d.InitializeXmlContainer(settingsXmlFile);

// Or, if XmlContainerInitializer supports some base interface IContainerInitializer ...
var i = (IContainerInitializer)containerInitializer;
IBaseContainer container = i.InitializeXmlContainer(settingsXmlFile);