Home > Backend Development > C++ > Can I Dynamically Instantiate a .NET Class from Just a DLL and Class Name?

Can I Dynamically Instantiate a .NET Class from Just a DLL and Class Name?

Barbara Streisand
Release: 2025-01-19 09:02:08
Original
569 people have browsed it

Can I Dynamically Instantiate a .NET Class from Just a DLL and Class Name?

Dynamic loading and instantiation of .NET assemblies

Having only a DLL and class name, is it possible to dynamically create an object without explicitly referencing an assembly in the project? This class conforms to the interface specification, allowing you to cast it to an interface after instantiation.

Assembly and type information

  • Assembly name: library.dll
  • Type name: Company.Project.Classname

Solution

Yes. Using Assembly.LoadFrom you can load an assembly into memory. You can then use Activator.CreateInstance to create an instance of the desired type. Using reflection you have to search for the type first:

Assembly assembly = Assembly.LoadFrom("MyNice.dll");

Type type = assembly.GetType("MyType");

object instanceOfMyType = Activator.CreateInstance(type);
Copy after login

Improvement plan

Once you have the assembly file name and type name, you can use Activator.CreateInstance(assemblyName, typeName) to instruct the .NET type resolution mechanism to determine the type. To handle the case where this attempt fails, you can wrap it in a try/catch block and then search the directory where the supplementary assembly may be stored. At this point, you'll use the method mentioned earlier.

The above is the detailed content of Can I Dynamically Instantiate a .NET Class from Just a DLL and Class Name?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template