c# - 为什么我们有这么多种程序集加载方法?

标签 c# .net vb.net clr

据我所知,有 3 种方法可以将程序集加载到 AppDomain 中:

  • Assembly.Load()
  • Assembly.LoadFrom()
  • Assembly.LoadFile()

LoadFrom() 方法将程序集文件路径作为其参数,但文件路径只是提供程序集标识信息作为 CLR 的线索。 LoadFrom() 方法仍然在内部使用该身份信息调用 Load()。因此,LoadFrom(filepath) 很可能会加载与文件路径指定的程序集完全不同的程序集。但温和的 LoadFile() 方法只会加载我们指定的程序集。

我想知道为什么我们需要 LoadFrom() 方法?它只会增加困惑和陷阱。有没有只适用LoadFrom()的场景?

非常感谢。

最佳答案

实际上对此有很多讨论,有一些不同的意见:

Difference between LoadFile and LoadFrom with .NET Assemblies?

http://geekswithblogs.net/rupreet/archive/2010/02/16/137988.aspx

http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/3bdaf65c-520c-4a1a-a825-fc2ca2957bf3

http://blogs.microsoft.co.il/blogs/sasha/archive/2007/03/06/Assembly-Load-Contexts-Subtleties.aspx

回答您关于为什么需要 LoadFrom() 方法的问题。好吧,这似乎归结为想要从特定位置和依赖项加载。 Load() 解决依赖关系,但不允许您选择程序集的位置(即,在尝试找到程序集的位置上存在一组“探测”结构)。 LoadFile() 保证您将加载指定为字符串参数的程序集,但不解析依赖项。 LoadFrom() 不保证将加载您在路径中提供的程序集(即,如果已加载具有相似标识的程序集),但它确实为您解决了依赖关系。

来自 MSDN

Use the LoadFile method to load and examine assemblies that have the same identity, but are located in different paths. LoadFile does not load files into the LoadFrom context, and does not resolve dependencies using the load path, as the LoadFrom method does. LoadFile is useful in this limited scenario because LoadFrom cannot be used to load assemblies that have the same identities but different paths; it will load only the first such assembly.

根据我收集的信息,似乎形成了一种不稳定的共识,即应该远离 LoadFile(),如果可以的话使用 Load(),如果需要则使用 LoadFrom()。但我也看到人们说远离 LoadFrom()。

作为一个数据点,在 Ecma CLI 标准 ( http://www.ecma-international.org/publications/standards/Ecma-335.htm ) 中,我们仅标准化了 Assembly.Load(string) 方法,其中字符串是程序集名称。

关于c# - 为什么我们有这么多种程序集加载方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3792010/

相关文章:

c# - 从 XML 模式生成 C# 类文件

c# - 谁有我可以看到的异步网络请求的简单实现?

c# - 如何使用 TextChanged 属性将 12 个连续数字粘贴到 4 个文本框中?

c# - ASP.NET MVC5 自定义身份验证

.net - 强制 WPF 滚动条仅落在整数值上

c# - 在 C#/VB.NET 中解码 T-SQL CAST

c# - gmail不再发送邮件了

c# - 为什么 null 不是 Nullable<> 类型的实例?

sql-server - 启动时在 VB.NET 应用程序中选择连接字符串

.net - 什么 groupbox 方法(如果有)监视单选按钮选择?