Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将窗体添加到dll时出现null异常_C#_Winforms_Interface - Fatal编程技术网

C# 将窗体添加到dll时出现null异常

C# 将窗体添加到dll时出现null异常,c#,winforms,interface,C#,Winforms,Interface,我有一个简单的dll。我使用“接口”将dll加载到主应用程序中。问题是我希望dll具有表单,所以我将一个新表单添加到dll项目中。但每当我将dll加载到主应用程序并尝试调用任何方法时,我都会得到:null异常: .. Type[] pluginTypes = Assembly.LoadFile(s).GetTypes(); foreach (Type t in pluginTypes){ M.ModuleInterface module = Activator.Cr

我有一个简单的dll。我使用“接口”将dll加载到主应用程序中。问题是我希望dll具有表单,所以我将一个新表单添加到dll项目中。但每当我将dll加载到主应用程序并尝试调用任何方法时,我都会得到:null异常:

   ..
   Type[] pluginTypes = Assembly.LoadFile(s).GetTypes();

   foreach (Type t in pluginTypes){
     M.ModuleInterface module = Activator.CreateInstance(t) as M.ModuleInterface;
     module.ReadAll(); // exception
   }

   // Exception I'm getting
   t.GenericParameterAttributes' threw an exception of type 'System.InvalidOperationException'

如果我从dll中删除表单,异常就会消失,一切都很正常。如何添加表单并修复此异常?谢谢

我认为这是因为您没有在dll方法中初始化表单。尝试将表单作为参数传递。

我认为这是因为您没有在dll方法中初始化表单。尝试将表单作为参数传递。

这可能会发生,因为dll中并非所有类型都实现
ModuleInterface
接口

试试这个:

Type[] pluginTypes = Assembly.LoadFile(s).GetTypes();

foreach (Type t in pluginTypes)
{
    if(t.GetInterfaces().Contains(typeof(ModuleInterface)))
    {
        var module = (ModuleInterface)Activator.CreateInstance(t);
        module.ReadAll(); // exception
    }
}

这可能是因为dll中并非所有类型都实现
ModuleInterface
接口

试试这个:

Type[] pluginTypes = Assembly.LoadFile(s).GetTypes();

foreach (Type t in pluginTypes)
{
    if(t.GetInterfaces().Contains(typeof(ModuleInterface)))
    {
        var module = (ModuleInterface)Activator.CreateInstance(t);
        module.ReadAll(); // exception
    }
}

在循环之前,应筛选所需类型的所有元素:

foreach(Type t in pluginTypes.Where(type=>typeof(M.ModuleInterface).IsAssignableFrom(type))){
   M.ModuleInterface module = Activator.CreateInstance(t) as M.ModuleInterface;
   module.ReadAll();
}

在循环之前,应筛选所需类型的所有元素:

foreach(Type t in pluginTypes.Where(type=>typeof(M.ModuleInterface).IsAssignableFrom(type))){
   M.ModuleInterface module = Activator.CreateInstance(t) as M.ModuleInterface;
   module.ReadAll();
}

您的表单实现了模块接口吗?您考虑过MEF吗?它更适合于编写可插拔的应用程序。您的表单是否实现了模块接口?您考虑过MEF吗?它更适合于编写可插拔的应用程序。