如何通过名称获取 C#.Net 程序集?
有没有类似的东西:
AppDomain.CurrentDomain.GetAssemblyByName("TheAssemblyName")
所以我们可以直接获取特定的程序集,而不是循环遍历 AppDomain.CurrentDomain.GetAssemblies() 。
Is there something like:
AppDomain.CurrentDomain.GetAssemblyByName("TheAssemblyName")
so instead of looping through AppDomain.CurrentDomain.GetAssemblies()
, we could just get the specific assembly directly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您是否尝试过查看 Assembly.Load(...)?
Have you tried looking at Assembly.Load(...)?
我用LINQ解决了
I resolved with LINQ
这取决于您想要实现的目标。
如果您只想获取程序集,那么您应该调用 System.Reflection.Assembly.Load()(如前所述)。这是因为 .NET 会自动检查程序集是否已加载到当前 AppDomain 中,如果已加载则不会再次加载。
如果您只是想检查程序集是否已加载(可能出于某些诊断原因),那么您必须循环遍历所有已加载的程序集。
您可能想要循环的另一个原因是,如果您只知道一些程序集信息(例如,您不确定版本)。也就是说,您的了解足以“看到它就认出它”,但还不足以加载它。不过,这是一个相当模糊且不太可能发生的情况。
It depends on what you're trying to accomplish.
If you just want to get the assembly, then you should call
System.Reflection.Assembly.Load()
(as already pointed out). That's because .NET automatically checks if the assembly has already been loaded into the current AppDomain and doesn't load it again if it has been.If you're just trying to check whether the assembly has been loaded or not (for some diagnostics reason, perhaps) then you do have to loop over all the loaded assemblies.
Another reason you might want to loop is if you know only some of the assembly information (eg. you're not sure of the version). That is, you know enough to "recognise it when you see it", but not enough to load it. That is a fairly obscure and unlikely scenario, though.
如果这是您引用的程序集,我喜欢编写如下所示的类:
然后每当您需要引用该程序集时:
如果将其标记为
sealed
而不是static,那么你可以将它作为通用参数传递,它可以让你用反射做一些事情。
If this is an assembly you have referenced, I like to write a class like the following:
and then whenever you need a reference to that assembly:
If you mark it
sealed
instead ofstatic
, then you can pass it as a generic argument which can allow you to do some things with reflection.对于那些只需要访问程序集元数据(版本等)的人,请查看 Assembly.ReflectionOnlyLoad(name),它只能加载元数据,可能会节省内存和 IO。
For those who just need to access the assembly's metadata (version, etc.) check out Assembly.ReflectionOnlyLoad(name), which is able to load only the metadata, possibly saving on memory and IO.
您可以编写一个扩展方法来完成您的需要。
此方法只会枚举已加载的程序集,如果您可能需要加载它,请使用已接受答案中的
Assembly.Load
。然后,您可以像这样在 AppDomain 上调用此方法:
如果 SomeAssembly 加载到当前 AppDomain 中,该方法将返回它,否则将返回
null
。You can write an extension method that does what you need.
This method will only enumerate loaded assemblies, if you possibly need to load it, use
Assembly.Load
from the accepted answer.Then you call this method on an AppDomain like this:
If SomeAssembly is loaded into the current AppDomain the method will return it, otherwise it will return
null
.查看 System.Reflection.Assembly 类,特别是 Load 方法: MSDN
Have a look at the System.Reflection.Assembly class, in particular the Load method: MSDN