Skip to main content
 首页 » 编程设计

c#之从动态加载程序集创建对象并将其转换为接口(interface) (.NET 2.0)

2024年02月23日12hnrainll

我在动态加载程序集并将其转换为接口(interface)时遇到问题。我的错误在哪里?

主应用(加载插件):

namespace Console_IFce_Test 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            Console.WriteLine("Press any key to find IPlugin library..."); 
            Console.ReadKey();             
 
            string[] files = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.dll"); 
            Console.WriteLine("Loading assembly: {0}", Path.GetFileName(files[0])); 
 
            Assembly asm = Assembly.LoadFrom(files[0]); 
            //Trying this, but still have problems 
            //Assembly asm = Assembly.Load(File.ReadAllBytes(files[0]));  
 
            foreach (Type t in asm.GetTypes()) 
            { 
                Console.WriteLine("Searching in type {0}... ", t.FullName); 
 
                foreach (Type iface in t.GetInterfaces()) 
                { 
                    Console.WriteLine("Interface found: {0}", iface.FullName); 
                } 
 
                if (t is IPlugin) 
                { 
                    Console.WriteLine("1 - IPlugin found!"); 
                    IPlugin plugin = (IPlugin)Activator.CreateInstance(t); 
                    return; 
                } 
 
                if (typeof(IPlugin).IsAssignableFrom(t)) 
                { 
                    Console.WriteLine("2 - IPlugin found!"); 
                    IPlugin plugin = (IPlugin)Activator.CreateInstance(t); 
                    return; 
                } 
            } 
 
            Console.WriteLine("All operations done! Press any key to exit..."); 
            Console.ReadKey(); 
        } 
    } 
} 

接口(interface):

namespace Console_IFce_Test 
{ 
    interface IPlugin 
    { 
        int GetZero(); 
    } 
} 

和插件:

namespace Library 
{ 
    public class Plugin : Console_IFce_Test.IPlugin 
    { 
        public int GetZero() 
        { 
            return 0; 
        } 
    } 
} 

在带有 .exe 的目录中 - 只有 1 个 .dll(插件)。所以,它的输出:

Press any key to find IPlugin library...  
Loading assembly: Library.dll  
Searching in type Console_IFce_Test.IPlugin...  
Searching in type Library.Plugin...  
Interface found: Console_IFce_Test.IPlugin  
All operations done! Press any key to exit... 

你看,那个程序在程序集中找到了 IPlugin 接口(interface),但是当我试图将它与接口(interface)(两个条件语句)进行比较时 - 它们返回 false。如果我尝试手动转换它 - 它会返回异常“无法转换”。

我发现了类似的问题:Two Types not equal that should be ,以及答案的作者写:

The same class / type loaded by different app domains [.NET] or class loaders [Java] will not compare equal and are not assignable to/from each other directly.

但是我不明白我该怎么办?以及如何?

请您参考如下方法:

您需要以某种方式让 .NET 将程序集加载到相同的上下文中,以便能够在这些程序集中的类型之间进行转换。

1- 将程序集放在应用程序路径或 GAC 中,以便 Load(而不是 LoadFrom)函数找到它。

2- 创建一个应用程序域并在那里完成所有工作。您可以完全控制在何处搜索应用程序域的程序集。

3- 使用加载项模型。

阅读本文以了解有关您的选择的更多信息:Best Practices for Assembly Loading