C# 如何在 .Net 中获取给定类型的程序集(System.Reflection.Assembly)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1141121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:13:02  来源:igfitidea点击:

How to get the assembly (System.Reflection.Assembly) for a given type in .Net?

c#.netreflection.net-assembly

提问by Fabio de Miranda

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?

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

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

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

采纳答案by jpj625

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.

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

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.

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

回答by John Saunders

Type.GetType(typeNameString).Assembly

回答by Matthew Scharley

Assembly.GetAssembly(typeof(System.Int32))

Replace System.Int32with whatever type you happen to need. Because it accepts a Typeparameter, you can do just about anything this way, for instance:

替换System.Int32为您碰巧需要的任何类型。因为它接受一个Type参数,所以你可以用这种方式做任何事情,例如:

string GetAssemblyLocationOfObject(object o) {
    return Assembly.GetAssembly(o.GetType()).Location;
}

回答by Sam Harwell

If you can use it, this syntax is the shortest/cleanest:

如果你可以使用它,这个语法是最短/最干净的:

typeof(int).Assembly

回答by MCattle

I've adapted the accepted answer for my own purposes (returning the assembly object instead of the assembly name), and refactored the code for VB.NET and LINQ:

我已经根据自己的目的改编了接受的答案(返回程序集对象而不是程序集名称),并重构了 VB.NET 和 LINQ 的代码:

Public Function GetAssemblyForType(typeName As String) As Assembly
    Return AppDomain.CurrentDomain.GetAssemblies.FirstOrDefault(Function(a) a.GetType(typeName, False, True) IsNot Nothing)
End Function

I'm just sharing it here if anyone else would like a LINQy solution to the accepted answer.

如果其他人想要对已接受答案的 LINQy 解决方案,我只是在这里分享它。