如何在 .Net 中获取给定类型的程序集(System.Reflection.Assembly)? [英] How to get the assembly (System.Reflection.Assembly) for a given type in .Net?

查看:26
本文介绍了如何在 .Net 中获取给定类型的程序集(System.Reflection.Assembly)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 .Net 中,给定一个类型名称,是否有一种方法可以告诉我该类型是在哪个程序集(System.Reflection.Assembly 的实例)中定义的?

In .Net, given a type name, is there a method that tells me in which assembly (instance of System.Reflection.Assembly) that type is defined?

我假设我的项目已经引用了那个程序集,只需要知道它是哪个.

I assume that my project already has a reference to that assembly, just need to know which one it is.

推荐答案

Assembly.GetAssembly 假定您拥有该类型的实例,而 Type.GetType 假定您拥有包含程序集名称的完全限定类型名称.

Assembly.GetAssembly assumes you have an instance of the type, and Type.GetType assumes you have the fully qualified type name which includes assembly name.

如果你只有基本类型名称,你需要做更多这样的事情:

If you only have the base type name, you need to do something more like this:

public static String GetAssemblyNameContainingType(String typeName) 
{
    foreach (Assembly currentassembly in AppDomain.CurrentDomain.GetAssemblies()) 
    {
        Type t = currentassembly.GetType(typeName, false, true);
        if (t != null) {return currentassembly.FullName;}
    }

    return "not found";
}

这也假设您的类型是在根中声明的.您需要在名称中提供命名空间或封闭类型,或者以相同的方式进行迭代.

This also assumes your type is declared in the root. You would need to provide the namespace or enclosing types in the name, or iterate in the same manner.

这篇关于如何在 .Net 中获取给定类型的程序集(System.Reflection.Assembly)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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