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

查看:18
本文介绍了获取 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 并且没有位置/路径/文件路径属性.为了获取位置属性,我首先使用了 Assembly.Load(),然后使用了位置属性.我不希望加载程序集获得它们的路径,因为它们没有必要使用,并且因为 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().

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

现在这是我的方法的样子:

now this is how my method looks like:

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;
    }
}

现在唯一剩下的问题是 type.Assembly.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?

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

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