获取类型中使用的程序集的路径

编程入门 行业动态 更新时间:2024-10-25 07:21:14
本文介绍了获取类型中使用的程序集的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要一个接受Type并返回该Type中使用的所有程序集的路径的方法。 我这样写:

I need a method that takes a Type and returns the paths of all assemblies that used in the type. I wrote this:

public static IEnumerable<string> GetReferencesAssembliesPaths(this Type type) { yield return type.Assembly.Location; foreach (AssemblyName assemblyName in type.Assembly.GetReferencedAssemblies()) { yield return Assembly.Load(assemblyName).Location; } }

通常此方法可以完成此工作,但有一些缺点:

Generally this method do the job, but have some disadvantages:

  • 我没有找到如何从类型本身获取引用的程序集/类型,所以我使用了type.Assembly .GetReferencedAssemblies()并获取整个程序集的引用,而不仅仅是与类型相关的引用。

  • I didn't found how to get the referenced assemblies/types from the type itself, so i used type.Assembly.GetReferencedAssemblies() and got the references of the whole assembly, not just those that related to the type.

type.Assembly.GetReferencedAssemblies()返回AssemblyName和没有location / path / filepath属性。为了获得location属性,我首先使用Assembly.Load(),然后使用location属性。我不希望加载程序集获取其路径,因为它们没有必要使用,并且因为Assembly.Load()可能因FileNotFoundException或BadImageFormatException而失败。

type.Assembly.GetReferencedAssemblies() returns AssemblyName and has no location/path/filepath property. To get the location property, i first used Assembly.Load() and then used the location property. I dont want load assemblies to get their path, because they not necessary used, and because Assembly.Load() can fail with FileNotFoundException or BadImageFormatException.

推荐答案

我认为我通过将Assembly.Load()替换为Assembly.ReflectionOnlyLoad()来解决了Assembly.Load()问题。

I think i solved the Assembly.Load() problem by replacing it to Assembly.ReflectionOnlyLoad().

现在这就是我的方法:

public static IEnumerable<string> GetReferencesAssembliesPaths(this Type type) { yield return type.Assembly.Location; foreach (AssemblyName assemblyName in type.Assembly.GetReferencedAssemblies()) { yield return Assembly.ReflectionOnlyLoad(assemblyName.FullName).Location; } }

现在剩下的唯一问题就是类型。 GetReferencedAssemblies(),如何从类型而不是从程序集获取引用的程序集?

now the only left problem is the type.Assembly.GetReferencedAssemblies(), how do i get referenced assemblies from the type rather than from the assembly?

更多推荐

获取类型中使用的程序集的路径

本文发布于:2023-11-13 12:07:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584317.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径   类型   程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!