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

前端 未结 5 1254
天涯浪人
天涯浪人 2020-12-09 14:41

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

相关标签:
5条回答
  • 2020-12-09 15:27
    Assembly.GetAssembly(typeof(System.Int32))
    

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

    string GetAssemblyLocationOfObject(object o) {
        return Assembly.GetAssembly(o.GetType()).Location;
    }
    
    0 讨论(0)
  • 2020-12-09 15:31

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

    typeof(int).Assembly
    
    0 讨论(0)
  • 2020-12-09 15:39

    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.

    0 讨论(0)
  • 2020-12-09 15:40

    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:

    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.

    0 讨论(0)
  • 2020-12-09 15:41
    Type.GetType(typeNameString).Assembly
    
    0 讨论(0)
提交回复
热议问题