繁体   English   中英

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

[英]Why does my code throw an Invalid Cast Exception? (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;
}

我的程序和程序集都具有以下两个接口:

using System;

namespace PluginInterface
{
public interface IPlugin
{
IPluginHost Host { get; set; }
string Name { get; }
string Description { get; }
string Author { get; }
string Version { get; }
System.Windows.Forms.Form MainInterface { get; }
void Initialize();
void Dispose();
void ReceivedMessage(PlayerIOClient.Message m);
void Disconnected();
}

public interface IPluginHost
{
void Say(string message);
void Send(PlayerIOClient.Message m);
void Send(string message_Type, params object[] paramss);
}
}

我要添加的班级/装配体:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using PluginInterface;

namespace ClassLibrary1
{

public class Plugin : IPlugin // <-- See how we inherited the IPlugin interface?
{
public Plugin()
{

}

string myName = "Title";
string myDescription = "Descrip";
string myAuthor = "Me";
string myVersion = "0.9.5";


IPluginHost myHost = null;
Form1 myMainInterface = new Form1();



public string Description
{
get { return myDescription; }
}

public string Author
{
get { return myAuthor; }
}

public IPluginHost Host
{

get { return myHost; }
set { myHost = value; }
}

public string Name
{
get { return myName; }
}

public System.Windows.Forms.Form MainInterface
{
get { return myMainInterface; }
}

public string Version
{
get { return myVersion; }
}

public void Initialize()
{
//This is the first Function called by the host...
//Put anything needed to start with here first
MainInterface.Show();
}

public void ReceivedMessage(PlayerIOClient.Message m)
{

}
public void Disconnected()
{

}

public void Dispose()
{
MainInterface.Dispose();
}

}
}

非常感谢所有帮助。

我的程序和程序集都具有以下两个接口:

有你的问题。

两个不同程序集中的两个相同接口创建两个不同(且不相关)的类型。

您需要在单个程序集中定义接口并添加对它的引用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM