C # dynamically create and use an assembly, class, method, and field (1)

Source: Internet
Author: User
Tags emit

Sometimes the whole project architecture also needs to dynamically create the assembly, so how to create the Assembly, please come with me to learn.

First, you need to know what technologies are used to dynamically create these types? In fact, as long as the related Dynamically Loaded assembly and classes use reflection, dynamic creation also uses reflection, which is a reflection technology! That is, the object or data is mapped into an object or assembly and saved.

First, we need to know what type each dynamic type is represented in. net.

Assembly: System. Reflection. Emit. AssemblyBuilder (defines and represents a dynamic assembly)

Constructor: System. Reflection. Emit. ConstructorBuilder (constructor that defines and represents dynamic classes)

Custom Attributes: System. Reflection. Emit. CustomAttributeBuilder (helps to generate custom attributes and generate class attributes using parameters passed by constructors)

Enumeration: System. Reflection. Emit. EnumBuilder (description and enumeration type)

Event: System. Reflection. Emit. EventBuilder (Class-defined event)

Field: System. Reflection. Emit. FieldBuilder (defines and represents a field. This class cannot be inherited)

Local variable: System. Reflection. Emit. LocalBuilder (local variable in the method or constructor)

Method: System. Reflection. Emit. MethodBuilder (defines and represents a dynamic class method (or constructor ))

Module: System. Reflection. Emit. ModuleBuilder (defines and represents a module in a dynamic assembly)

Parameter: System. Reflection. Emit. ParameterBuilder (create or associate parameter information such as method parameters and event parameters)

Attribute: System. Reflection. Emit. PropertyBuilder (Property ))

Class: System. Reflection. Emit. TypeBuilder (define and create a new instance of the class at runtime)

With these types, we can basically dynamically create any types we need. Of course, many types that can be dynamically created cannot be described, if there is a need in the project, you can refer to MSDN and there are demos in it. The main problem is to understand the definition of each type. For example, assembly loading depends on AppDomain, A collection contains multiple modules. classes can be declared in the module, and methods, attributes, and fields can be created in the class. Methods can be created only in the class. Local variables are rules declared in the method body. It is very easy to understand MSDN.

1. How to create them dynamically

AppDomain: application domainAppDomainObject Representation) provides isolation, uninstallation, and security boundaries for the execution of managed code. AppDomain can load multiple assemblies at the same time to implement functions.

Assembly: In simple terms, it is a version-based and self-described binary file that uses the Common Language Runtime Library (CLR) as the host. (Description: definitions come from C # And. NET3.5 advanced programming (version 4 ))

Module: similar to the previous unit, used to separate different classes and types, and resource (resource, resource record is a string, image and other data, they are only transferred to the memory when needed ). Type Meta information is also part of the module. Multiple modules form an assembly.

Dynamic means dynamic creation and use when the program is running.

Let's look at the code. It's actually super simple.

// Dynamically create an assembly
AssemblyName DemoName = new AssemblyName ("DynamicAssembly ");
AssemblyBuilder dynamicAssembly = AppDomain. CurrentDomain. DefineDynamicAssembly (DemoName, AssemblyBuilderAccess. RunAndSave );
// Dynamically create a module
ModuleBuilder mb = dynamicAssembly. DefineDynamicModule (DemoName. Name, DemoName. Name + ". dll ");
// Dynamically create a class MyClass
TypeBuilder tb = mb. DefineType ("MyClass", TypeAttributes. Public );
// Dynamically create fields
FieldBuilder fb = tb. DefineField ("", typeof (System. String), FieldAttributes. Private );
// Create a constructor dynamically
Type [] clorType = new Type [] {typeof (System. String )};
ConstructorBuilder cb1 = tb. DefineConstructor (MethodAttributes. Public, CallingConventions. Standard, clorType );
// Generate command
ILGenerator ilg = cb1.GetILGenerator (); // generates Microsoft intermediate language (MSIL) commands
Ilg. Emit (OpCodes. Ldarg_0 );
Ilg. Emit (OpCodes. Call, typeof (object). GetConstructor (Type. EmptyTypes ));
Ilg. Emit (OpCodes. Ldarg_0 );
Ilg. Emit (OpCodes. Ldarg_1 );
Ilg. Emit (OpCodes. stdes, fb );
Ilg. Emit (OpCodes. Ret );
// Dynamically create attributes
PropertyBuilder pb = tb. DefineProperty ("MyProperty", PropertyAttributes. HasDefault, typeof (string), null );
// Dynamic creation method
MethodAttributes getSetAttr = MethodAttributes. Public | MethodAttributes. SpecialName;
MethodBuilder myMethod = tb. DefineMethod ("get_Property", getSetAttr, typeof (string), Type. EmptyTypes );
// Generate command
ILGenerator numberGetIL = myMethod. GetILGenerator ();
NumberGetIL. Emit (OpCodes. Ldarg_0 );
NumberGetIL. Emit (OpCodes. ldquo, fb );
NumberGetIL. Emit (OpCodes. Ret );
// Save the dynamically created assembly
DynamicAssembly. Save (DemoName. Name + ". dll ");

Article 2: C # dynamically create and use an assembly, class, method, and field (II)

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.