get assembly by class name

后端 未结 4 1026
青春惊慌失措
青春惊慌失措 2020-12-10 12:16

Is there any way to get the assembly that contains a class with name TestClass? I just know the class name, so I can\'t create an instance of that. And

4条回答
  •  悲&欢浪女
    2020-12-10 13:11

    Actually knowledge of classname is enough in most scenarios. MSDN says - If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

    Type neededType = Type.GetType("TestClass"); //or typeof(TestClass) 
    Assembly a = neededType.Assembly;
    

    In case you dont know the assembly containing type (though i cant imagine why) -

    Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
    Asssembly result = assemblies.FirstOrDefault(a=>a.GetType("TestClass",false)!=null);
    

    The only restriction - assembly containing TestClass should have been already loaded at the moment of calling such code.

    Hope this'll help. :)

提交回复
热议问题