C # A detailed introduction to using reflection to create an instance object of a class from a class name

Source: Internet
Author: User
This article mainly introduces the elaboration of C # using reflection to create a class from the class name of the instance object, "reflection" is actually the use of assembly metadata information, interested in small partners can refer to.

"Reflection" is actually the use of the assembly's meta-data information. Reflection can have many methods, and you should first import the System.Reflection namespace when you write your program.

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


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

2. To reflect a class in the current project (that is, the current project already refers to it) can be:


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, returns an object type, requires coercion of type conversion

3, can also be:


Type type = Type.GetType ("Fully qualified name of the class"); Dynamic obj = type. Assembly.createinstance (type);

4, different assemblies, then to load the call, the code is as follows:

System.Reflection.Assembly.Load ("assembly name (without file suffix name)"). CreateInstance ("namespace. Class name", false);

Such as:

The code is as follows:

Dynamic o = System.Reflection.Assembly.Load ("MyDll"). CreateInstance ("Mynamespace.a", false);

Note: because you want to use dynamic, you need to change the target to 4.0 if "one or more of the types required to compile the dynamic expression" is found at compile-time. Is the reference missing? " Error, because a reference is missing, the Miscorsoft.csharp class library is referenced in the project and can be compiled successfully after it is added.

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

Add:

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

2) The reflection function is very powerful, nothing can not be achieved. If you implement cross-assembly, use the first method to create an instance of the class and reflect the instance's fields, properties, methods, events ... It is then dynamically called.


  <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" > Assembly </param>///<returns></returns> public static T createinstance<t> (String fullName, String assemblyname) {String path = FullName + "," + A ssemblyname;//namespace. Type name, assembly type O = Type.GetType (path);//Load type Object obj = Activator.CreateInstance (o, true);//Root Create instance according to type return (T) obj;//type conversion and return}///<summary>//Create object instance///</summary>//<typepara M name= "T" > type of object to create </typeparam>//<param name= "AssemblyName" > type in the assembly name </param>///<param Name= "NameSpace" > Type of Namespace </param>//<param name= "ClassName" > type name </param>//<returns>& Lt;/returns> Public Static T createinstance<t> (String assemblyname, String NameSpace, String className) {try {str ing fullName = nameSpace + "." + classname;//namespace. Type name//This is the first notation of object ect = Assembly.Load (AssemblyName). CreateInstance (fullName);//load the assembly, create the namespace inside the assembly. Type name Instance return (T) ect;//type conversion and return//The following is the second notation//string Pat H = fullName + "," + assemblyname;//namespace. Type name, assembly//type o = Type.GetType (path);//load type//object obj = Activat Or.        CreateInstance (o, true);//Create instance by type//return (T) obj;//type conversion and return} catch {//exception, return type default value      return default (T); }    }  }
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.