获取类型中使用的程序集的路径 [英] Get paths of assemblies used in Type

查看:68
本文介绍了获取类型中使用的程序集的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个接受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?

这篇关于获取类型中使用的程序集的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆