get assembly by class name

后端 未结 4 1023
青春惊慌失措
青春惊慌失措 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

    From the Type objectType in the question, I assume you are actually after the type by name (not the assembly); so assuming the assembly is loaded and the type name is unique, LINQ may help:

    Type objectType = (from asm in AppDomain.CurrentDomain.GetAssemblies()
                       from type in asm.GetTypes()
                       where type.IsClass && type.Name == "TestClass"
                       select type).Single();
    object obj = Activator.CreateInstance(objectType);
    

    However, it may be better to work with the assembly-qualified name instead of the type name.

提交回复
热议问题