C # Reflection creates a class instance 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);

=======================================================
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.

C # Reflection creates a class instance 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.