我正在使用一个外部 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>();
}
如果你真的需要使用那个“aContainer”循环,你可以通过使用 MakeGenericType 来避免变量与类型的错误,就像这样:
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);
我是一名优秀的程序员,十分优秀!