Home > Backend Development > C++ > Can I Instantiate a Class at Runtime Knowing Only its DLL and Type Name?

Can I Instantiate a Class at Runtime Knowing Only its DLL and Type Name?

Linda Hamilton
Release: 2025-01-19 09:21:09
Original
496 people have browsed it

Can I Instantiate a Class at Runtime Knowing Only its DLL and Type Name?

Dynamic loading of assemblies and instantiated classes at runtime

Knowing only the DLL file name and class name, is it possible to instantiate an object at runtime without explicitly referencing the assembly in the project? This class usually implements an interface that allows type conversion after instantiation.

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

No file path

Cannot be used since there is no absolute DLL path. The DLL may be located in the application root, system32, or the GAC. Assembly.LoadFile

Solution

It can be done. Use

to load an assembly into memory. Then, use Assembly.LoadFrom to generate an instance of the desired type. First use reflection to find the type. Activator.CreateInstance

<code class="language-csharp">Assembly assembly = Assembly.LoadFrom("MyNice.dll");

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

object instanceOfMyType = Activator.CreateInstance(type);</code>
Copy after login

Improved solution

Given an assembly file name and a type name,

can be resolved to a type. This can be wrapped with a try/catch block for error handling. If that fails, directories where other assemblies may exist are searched and the previous methods are applied if necessary. Activator.CreateInstance(assemblyName, typeName)

The above is the detailed content of Can I Instantiate a Class at Runtime Knowing Only its DLL and Type Name?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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