C # uses reflection to create an instance object of a class from a class name

Source: Internet
Author: User

"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"); Loading assemblies (EXE or DLL)
Object 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 (); Get current Assembly
Object 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");
Object obj = type. Assembly.createinstance (type);

4, different assemblies, then to load the call, the code is as follows:
System.Reflection.Assembly.Load ("assembly name"). CreateInstance ("namespace. Class name", false);
Such as:
Object o = System.Reflection.Assembly.Load ("MyDll"). CreateInstance ("Mynamespace.a", false);


=======================================================
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 classReflectionhelper {/// <summary>        ///creating an Object instance/// </summary>        /// <typeparam name= "T" ></typeparam>        /// <param name= "FullName" >namespaces. Type name</param>        /// <param name= "AssemblyName" > Assembly</param>        /// <returns></returns>         Public StaticT createinstance<t> (stringFullName,stringAssemblyName) {            stringPath = FullName +","+ AssemblyName;//namespace. Type name, assemblyType o = type.gettype (path);//Load Type            Objectobj = Activator.CreateInstance (o,true);//to create an instance from a type            return(T) obj;//type conversions and returns        }        /// <summary>        ///creating an Object instance/// </summary>        /// <typeparam name= "T" >type of object to create</typeparam>        /// <param name= "AssemblyName" >The assembly name where the type is located</param>        /// <param name= "NameSpace" >Type is in the same namespace</param>        /// <param name= "ClassName" >type name</param>        /// <returns></returns>         Public StaticT createinstance<t> (stringAssemblyName,stringNameSpace,stringclassName) {            Try            {                stringFullName = NameSpace +"."+ ClassName;//namespaces. Type name//This is the first notation                ObjectECT = Assembly.Load (AssemblyName). CreateInstance (FullName);//loads the assembly, creating the namespace inside the assembly. Type name Instance                return(T) ECT;//type conversions and returns//Here's the second way .//string path = FullName + "," + AssemblyName;//namespace. Type name, assembly//Type o = type.gettype (path);//Load Type//Object obj = Activator.CreateInstance (o, true);//to create an instance from a type//return (T) obj;//type conversions and returns            }            Catch            {                //exception occurred, default value of return type                return default(T); }        }    }

C # uses reflection to create an instance object of a class from a class name

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.