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

Source: Internet
Author: User

View Original: Http://www.cnblogs.com/feiyuhuo/p/5793606.html#commentform

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)
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 (); Get 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:
Dynamic o = System.Reflection.Assembly.Load ("MyDll"). CreateInstance ("Mynamespace.a", false);

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

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.