我有一个 foreach 循环,它循环遍历类型列表并为每个类型创建一个实例。但是,当我构建时,它给出了 CS0246 错误(“找不到类型或命名空间......”)。这是代码的简化版本:
internal static class TypeManager
{
internal static void LoadTypes()
{
// Fill the list with types
// Create instances of each type
foreach (Type currType in Types)
{
Type aType = currType; // comiles fine
Object newObj = (currType)Activator.CreateInstance<currType>; // CS 0246
}
}
public static List<Type> Types;
}
编辑:后续问题
我的 foreach 循环现在看起来像这样:
foreach (Type currType in Types)
{
Types.Add((Type)Activator.CreateInstance(currType));
}
Types List 现在是 Object 类型
这编译得很好,但是当我运行它时,我得到以下信息:
Object reference not set to an instance of an object.
如果我将它分成两行,首先创建一个对象,然后将其添加到列表中,第一行很好(对象创建成功),但它给了我相同的错误消息。
编辑:更新代码示例
internal static LoadPlugins()
{
foreach (Type currType in pluginAssembly.GetTypes())
{
if (typeof(IPlugin).IsAssignableFrom(currType))
{
Assembly.LoadFrom(currFile.FullName);
Object pluginInstance = Activator.CreateInstance(currType); // Compiles and runs fine
Plugins.Add((IPlugin)pluginInstance); // NullReferenceException
break;
}
}
}
public static List<IPlugin> Plugins;