当前位置: 首页 > 编程语言 > C#

从加载的程序集中查找实现接口的对象-如何比较类型?分享

时间:2023-04-11 10:51:07 C#

从加载的程序集中查找实现接口的对象-如何比较类型?我有一个类将加载目录中的所有程序集,然后获取所有类型以查看它们是否实现了接口。我无法进行类型比较。在调试器中,如果比较总是失败,我会看到我的类型已加载(我感兴趣的类型)。如果我在本地使用相同的比较代码,我没有问题,我得到了预期的结果。我可以对类型接口进行比较,但我更想知道我做错了什么。测试://失败[事实]publicvoidFindISerialPortTest(){varpath=Directory.GetCurrentDirectory();varresults=FindImplementers.GetInterfaceImplementor(path);结果.Length.Should().Be(1);结果[0].Should().BeAssignableTo();}//通过[事实]publicvoidDoesTypeImplementInterfaceTest(){varmyType=typeof(SerialPortWrapper);varmyInterface=typeof(ISerialPort);FindImplementers.DoesTypeImplementInterface(myType,myInterface).Should().Be(true);}类:publicclassFindImplementers{publicstaticT[]GetInterfaceImplementor(stringdirectory){if(String.IsNullOrEmpty(directory)){returnnull;}//完整性检查DirectoryInfoinfo=newDirectoryInfo(directory);如果(!info.Exists){返回null;}//确保目录存在varimplementors=newList();foreach(FileInfofileininfo.GetFiles("*.dll"))//遍历目录下的所有dll文件{AssemblycurrentAssembly=null;类型[]类型=空;try{//使用反射,load程序集从磁盘存入内存currentAssembly=Assembly.LoadFile(file.FullName);类型=currentAssembly.GetTypes();}catch(Exceptionex){//忽略错误继续;}foreach(Typetypeintypes){if(!DoesTypeImplementInterface(type,typeof(T))){continue;}//创建实现T的类的实例并将其转换为类型varplugin=(T)Activator.CreateInstance(type);实施者。添加(插件);}}返回implementors.ToArray();}publicstaticboolDoesTypeImplementInterface(Typetype,TypeinterfaceType){return(type!=interfaceType&&interfaceType.IsAssignableFrom(type));好的-这给了我答案:invalidcastexception-when-using-assembly-loadfile这是更新的课程:以上是C#学习教程:从加载的程序集中查找实现接口的对象-如何比较类型?如果分享的内容对你有用,需要进一步了解C#学习教程,希望你多多关注——publicclassPluginLoader{publicstaticT[]GetInterfaceImplementor(stringdirectory){if(String.IsNullOrEmpty(目录)){返回空值;}//完整性检查DirectoryInfoinfo=newDirectoryInfo(目录);如果(!info.Exists){返回null;}//确保目录存在varimplementors=newList();foreach(FileInfofileininfo.GetFiles("*.dll"))//遍历目录下的所有dll文件{AssemblycurrentAssembly=null;尝试{varname=AssemblyName.GetAssemblyName(file.FullName);currentAssembly=Assembly.Load(名称);}catch(Exceptionex){继续;当前程序集。GetTypes().Where(t=>t!=typeof(T)&&typeof(T).IsAssignableFrom(t)).ToList().ForEach(x=>implementors.Add((T)Activator.CreateInstance(x)));}返回implementors.ToArray();}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:

最新推荐
猜你喜欢