我需要一个接受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?
更多推荐
获取类型中使用的程序集的路径
发布评论