SoFunction
Updated on 2025-03-07

Detailed explanation of C# Using reflection to create class instance objects based on class name

"Reflection" is actually to use the metadata information of the assembly. There are many ways to reflect. Please import the namespace first when writing a program.

1. Suppose you want to reflect a class in a DLL and do not reference it (i.e. an unknown type):

Assembly assembly = ("Assembly path, cannot be a relative path"); // Loading assembly (EXE or DLL)dynamic obj = ("Full-qualified name of a class (i.e. including namespace)"); // Create an instance of a class 

2. To reflect the class in the current project (that is, the current project has referenced it) can be:

Assembly assembly = (); // Get the current assemblydynamic obj = ("Full-qualified name of a class (i.e. including namespace)"); 
// Create an instance of a class,Return as object type,需要强制type转换

3. It can also be:

Type type = ("Full-qualified name of the class"); 
dynamic obj = (type); 

4. For different assembly, the call needs to be loaded, the code is as follows:

("Assembly name (excluding file suffix name)").CreateInstance("namespace.class name", false);

like:

Copy the codeThe code is as follows:

dynamic o = ("MyDll").CreateInstance("", false);

Notice:Since dynamic is used, you need to change the target to 4.0. If the error "One or more types required to compile dynamic expressions cannot be found. Is there a reference missing?" is because a reference is missing. The class library is referenced in the project and the compilation will be successful after adding it.

=======================================================

Replenish:

1) When reflecting creating an instance of a certain class, it is necessary to ensure that the fully qualified name of the class (namespace + class name) is used. Returning null means that searching for relevant information in metadata failed (reflection failed). Please make sure that the fully qualified name of the class is used when reflecting.

2) The reflection function is very powerful and nothing can be achieved. If you implement "cross assembly", please use the first method to create an instance of the class, and reflect the fields, properties, methods, events of the instance... and then call it dynamically.

  /// <summary>
  /// Reflection help class  /// </summary>
  public static class ReflectionHelper
  {
    /// <summary>
    /// Create an object instance    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="fullName">namespace.type name</param>    /// <param name="assemblyName">assembly</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public static T CreateInstance&lt;T&gt;(string fullName, string assemblyName)
    {
      string path = fullName + "," + assemblyName;// Namespace. Type name, assembly      Type o = (path);//Loading type      object obj = (o, true);//Create instances based on type      return (T)obj;//Type conversion and return    }

    /// &lt;summary&gt;
    /// Create an object instance    /// &lt;/summary&gt;
    /// <typeparam name="T">Type of the object to be created</typeparam>    /// <param name="assemblyName">Assembly Name of the type</param>    /// <param name="nameSpace">The namespace of type</param>    /// <param name="className">Type name</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public static T CreateInstance&lt;T&gt;(string assemblyName, string nameSpace, string className)
    {
      try
      {
        string fullName = nameSpace + "." + className;// Namespace. Type name        //This is the first way to write        object ect = (assemblyName).CreateInstance(fullName);//Load the assembly and create the namespace. Type name instance in the assembly        return (T)ect;//Type conversion and return        //The following is the second way of writing        //string path = fullName + "," + assemblyName;// Namespace. Type name, assembly        //Type o = (path);//Loading type        //object obj = (o, true);//Create instances based on type        //return (T)obj;//Type conversion and return      }
      catch
      {
        //Exception occurs, return the default value of the type        return default(T);
      }
    }
  }

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.