Home >Backend Development >C++ >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
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:
<code class="language-csharp">Assembly assembly = Assembly.LoadFrom("MyNice.dll"); Type type = assembly.GetType("MyType"); object instanceOfMyType = Activator.CreateInstance(type);</code>
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!