[英]C# - Error casting object to interface
是的,有類似的問題,但沒有一個解決了我的問題。 我用三個項目創建了一個新的解決方案:
ICrawler.cs代碼:
namespace Shared.Data.Structures
{
public interface ICrawler
{
void SayHello();
}
}
FP.cs代碼:
using System;
using Shared.Data.Structures;
namespace FirstPlugin
{
public class FP : ICrawler
{
public void SayHello() {
Console.WriteLine("Hello From FirstPlugin.dll");
}
}
}
Program.cs代碼:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using Shared.Data.Structures;
namespace MainApp
{
class Program
{
static void Main(string[] args) {
ICollection<ICrawler> plugins = GenericPluginLoader<ICrawler>.LoadPlugins(Directory.GetCurrentDirectory() + "\\modules");
Console.ReadKey();
}
}
public static class GenericPluginLoader<T>
{
public static ICollection<T> LoadPlugins(string path) {
string[] dllFileNames = null;
if (Directory.Exists(path)) {
dllFileNames = Directory.GetFiles(path, "*.dll");
ICollection<Assembly> assemblies = new List<Assembly>(dllFileNames.Length);
foreach (string dllFile in dllFileNames) {
AssemblyName an = AssemblyName.GetAssemblyName(dllFile);
Assembly assembly = Assembly.Load(an);
assemblies.Add(assembly);
}
Type pluginType = typeof(T);
ICollection<Type> pluginTypes = new List<Type>();
foreach (Assembly assembly in assemblies) {
if (assembly != null) {
Type[] types = assembly.GetTypes();
foreach (Type type in types) {
if (type.IsInterface || type.IsAbstract) {
continue;
}
else {
if (type.GetInterface(pluginType.FullName) != null) {
Console.WriteLine("ICrawler name: {0}", typeof(ICrawler).AssemblyQualifiedName);
Console.WriteLine("Type name: {0}", type.GetInterface(pluginType.FullName).AssemblyQualifiedName);
/*
Output:
ICrawler name: Shared.Data.Structures.ICrawler, MainApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
Type name: Shared.Data.Structures.ICrawler, FirstPlugin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
*/
pluginTypes.Add(type);
}
}
}
}
}
ICollection<T> plugins = new List<T>(pluginTypes.Count);
foreach (Type type in pluginTypes) {
T plugin = (T)Activator.CreateInstance(type);
plugins.Add(plugin);
}
return plugins;
}
return null;
}
}
}
我收到了這個漂亮的錯誤:
附加信息:無法將類型為“ FirstPlugin.FP”的對象轉換為類型為“ Shared.Data.Structures.ICrawler”
在這一行(Program.cs):
T plugin = (T)Activator.CreateInstance(type);
我決定創建此解決方案並復制粘貼確切的GenericPluginLoader
源(來自MSDN )。
我正在處理的項目具有不同的代碼,但是發生相同的錯誤。
此代碼有什么問題?
我的構建輸出:
PS:英語不是我的母語,所以...您知道(╭☞͠°͟ʖ°)╭☞。
共享項目將其源文件直接編譯到引用它們的每個項目中。
因此,您有兩個ICrawler
接口,每個程序集中一個,它們不是同一類型(即使它們是相同的)。
您正在嘗試將新實例強制轉換為未實現的接口副本; 你不能那樣做。
您應該使用普通的類庫,而不是共享項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.