C uses reflection to create instance objects of classes according to class names

  • 2021-12-09 09:47:54
  • OfStack

"Reflection" is actually taking advantage of the assembly's metadata information. Reflection can be done in many ways. Please import the System. Reflection namespace first when writing a program.

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


Assembly assembly = Assembly.LoadFile(" Assembly path, cannot be a relative path "); //  Load the assembly ( EXE  Or  DLL )  
dynamic obj = assembly.CreateInstance(" The fully qualified name of the class (that is, including the namespace) "); //  Create an instance of a class  

2. To reflect the class in the current project (that is, the current project already references it), you can:


Assembly assembly = Assembly.GetExecutingAssembly(); //  Gets the current assembly  
dynamic obj = assembly.CreateInstance(" The fully qualified name of the class (that is, including the namespace) "); 
//  Creates an instance of the class and returns the  object  Type, you need to force type conversion 

3. It can also be:


Type type = Type.GetType(" The fully qualified name of the class "); 
dynamic obj = type.Assembly.CreateInstance(type); 

4. If there are different assemblies, the call should be loaded. The code is as follows:

System. Reflection. Assembly. Load ("Assembly name (excluding file suffix name)"). CreateInstance ("Namespace. Class name", false);

Such as:


dynamic o = System.Reflection.Assembly.Load("MyDll").CreateInstance("MyNameSpace.A", false);

Note: Since dynamic is used, target needs to be changed to 4.0. If the "1 or more types needed to compile dynamic expressions cannot be found. Is there a missing reference?" Appears at compile time. Error, is due to the lack of a reference, in the project reference Miscorsoft. CSharp class library, after the addition can be compiled successfully.

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

Additional:

1) Reflection When creating an instance of a class, you must ensure that the fully qualified name of the class is used (namespace + class name). The Type. GetType method returns null, which means that the search for relevant information in metadata failed (reflection failed). Make sure that the fully qualified name of the class is used for reflection.

2) Reflection is so powerful that nothing can't be achieved. If you implement "cross-assembly", use method 1 to create an instance of a class, reflect its fields, properties, methods, events... and then call it dynamically.


  /// <summary>
  ///  Reflection helper 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"> Assemblies </param>
    /// <returns></returns>
    public static T CreateInstance<T>(string fullName, string assemblyName)
    {
      string path = fullName + "," + assemblyName;// Namespace . Type name , Assemblies 
      Type o = Type.GetType(path);// Load type 
      object obj = Activator.CreateInstance(o, true);// Create an instance from a type 
      return (T)obj;// Type conversion and return 
    }

    /// <summary>
    ///  Create an object instance 
    /// </summary>
    /// <typeparam name="T"> The type of object to create </typeparam>
    /// <param name="assemblyName"> The name of the assembly where the type is located </param>
    /// <param name="nameSpace"> Namespace of type </param>
    /// <param name="className"> Type name </param>
    /// <returns></returns>
    public static T CreateInstance<T>(string assemblyName, string nameSpace, string className)
    {
      try
      {
        string fullName = nameSpace + "." + className;// Namespace . Type name 
        // This is the first 1 Kinds of writing 
        object ect = Assembly.Load(assemblyName).CreateInstance(fullName);// Load the assembly and create the   Namespace . Type name   Instances 
        return (T)ect;// Type conversion and return 
        // The following is the number 2 Kinds of writing 
        //string path = fullName + "," + assemblyName;// Namespace . Type name , Assemblies 
        //Type o = Type.GetType(path);// Load type 
        //object obj = Activator.CreateInstance(o, true);// Create an instance from a type 
        //return (T)obj;// Type conversion and return 
      }
      catch
      {
        // Exception occurred, return the default value of type 
        return default(T);
      }
    }
  }


Related articles: