小编use*_*208的帖子

为什么我的代码会抛出无效的强制转换异常?(C#)?

错误信息:System.InvalidCastException:无法将类型为"ClassLibrary1.Plugin"的对象强制转换为"PluginInterface.IPlugin".

我正在尝试做的是让我的程序访问一个程序集并运行它可能具有的任何东西.这会加载.dll

private void AddPlugin(string FileName)
{
Assembly pluginAssembly = Assembly.LoadFrom(FileName);
foreach (Type pluginType in pluginAssembly.GetTypes())
{
if (pluginType.IsPublic)
{
if (!pluginType.IsAbstract)
{
Type typeInterface = pluginType.GetInterface("PluginInterface… true);
if (typeInterface != null)
{
Types.AvailablePlugin newPlugin = new Types.AvailablePlugin();
newPlugin.AssemblyPath = FileName;
newPlugin.Instance = (IPlugin)Activator.CreateInstance(plugin…
// Above line throws exception.

newPlugin.Instance.Initialize();
this.colAvailablePlugins.Add(newPlugin);
newPlugin = null;
}
typeInterface = null;
}
}
}
pluginAssembly = null;
}
Run Code Online (Sandbox Code Playgroud)

我的程序和程序集都有这两个接口:

using System;

namespace PluginInterface
{
public interface IPlugin
{
IPluginHost Host { get; set; …
Run Code Online (Sandbox Code Playgroud)

.net c# dll .net-assembly

2
推荐指数
1
解决办法
977
查看次数

标签 统计

.net ×1

.net-assembly ×1

c# ×1

dll ×1