为什么 Assembly.GetTypes() 需要引用?
我想从程序集中获取所有类型,但我没有引用,也不关心它们。查找接口类型与引用有什么关系?我有办法解决这个问题吗?
Assembly assembly = Assembly.LoadFrom(myAssemblyPath);
Type[] typeArray = assembly.GetTypes();
投掷: 文件未找到异常 无法加载文件或程序集“某些引用的程序集”或其依赖项之一。系统找不到指定的文件。
I want to get all of the types from my assembly, but I don't have the references, nor do I care about them. What does finding the interface types have to do with the references? and is there a way for me to get around this?
Assembly assembly = Assembly.LoadFrom(myAssemblyPath);
Type[] typeArray = assembly.GetTypes();
Throws:
FileNotFoundException
Could not load file or assembly 'Some referenced assembly' or one of its dependencies. The system cannot find the file specified.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
加载程序集还需要加载其所有依赖项,因为程序集中的代码可以在加载后执行(实际上不运行任何内容而仅反映它并不重要)。
要加载程序集以明确反映它的目的,您需要将其加载到仅反射上下文,例如
ReflectionOnlyLoadFrom
。这也不需要加载任何引用的程序集,但随后您将无法运行代码,并且反射有时会比您习惯的更尴尬。Loading an assembly requires all of its dependencies to be loaded as well, since code from the assembly can be executed after it's loaded (it doesn't matter that you don't actually run anything but only reflect on it).
To load an assembly for the express purpose of reflecting on it, you need to load it into the reflection-only context with e.g.
ReflectionOnlyLoadFrom
. This does not require loading any referenced assemblies as well, but then you can't run code and reflection becomes a bit more awkward than what you 're used to at times.它似乎是仅获取程序集中定义的类型的重复项,其中解为:
It seems to be a duplicate of Get Types defined in an assembly only, where the solution is:
为了加载程序集,有必要加载程序集的依赖项。例如,如果您的程序集包含返回
XmlNode
的类型,那么您将必须加载System.Xml.dll
In order to load the assembly, it's necessary to load the assembly's dependencies. If, for example, your assembly contains a type that returns an
XmlNode
then you will have to loadSystem.Xml.dll
使用仅反射上下文的替代方法可能是 Mono.Cecil< /a> 由 Jb Evain 提供,也可以通过 NuGet 获取。
An alternative to using the reflection only context might be Mono.Cecil by Jb Evain which is also available via NuGet.