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

Source: Internet
Author: User

The previous section describes how to create a dynamic table. This section describes how to use it to create a table. Of course, this is also very important, right. If a dynamic type is created but not used, what is the purpose of creating it. Today, let's learn how to dynamically use the dynamically created types.

Of course, as in the previous chapter, we need to understand the usage types of these dynamic types.

Class: Use System. Type (the reflection Type is used at any time, isn't it ?)

Constructor: System. Reflection. ConstructorInfo (discovers the attributes of the class constructor and provides access to the meta data of the constructor)

Event: System. Reflection. EventInfo (discovers event attributes and provides access to Event metadata)

Field: System. Reflection. FieldInfo (discovers field attributes and provides access to field metadata)

Method: System. Reflection. MemberInfo (obtains information about member attributes and provides access to Member metadata)

Member: System. Reflection. MemberInfo (obtains information about member attributes and provides access to Member metadata)

Parameter: System. Reflection. ParameterInfo (discovers parameter attributes and provides access to parameter metadata)

Attribute: System. Reflection. PropertyInfo (Attribute of Property and access to Property metadata)

This is also an extended type of reading, but you should first understand it. If you do not know it, you may not be able to start using dynamic types.

Today I made a Demo. Let's go to the Demo first and explain how the program is executed.

/Dynamically created dynamic types

Public static Type DynamicCreateType ()
{
// 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 ("myField", 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_Field", 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 );
// Use a dynamic class to create a type
Type classType = tb. CreateType ();
// Save the dynamically created Assembly (the Assembly will be saved under the program directory for debugging)
DynamicAssembly. Save (DemoName. Name + ". dll ");
// Create a class
Return classType;
}

 

Main method of execution

Static void Main (string [] args)
{
// Dynamically created class type
Type classType = DynamicCreateType ();
// Call a constructor with Parameters
Type [] ciParamsTypes = new Type [] {typeof (string )};
Object [] ciParamsValues = new object [] {"Hello World "};
ConstructorInfo ci = classType. GetConstructor (ciParamsTypes );
Object Vector = ci. Invoke (ciParamsValues );
// Call Method
Object [] methedParams = new object [] {};
Console. WriteLine (classType. InvokeMember ("get_Property", BindingFlags. InvokeMethod, null, Vector, methedParams ));
Console. ReadKey ();
}

 

This program first calls the DynamicCreateType () method to create a dynamic type, which is almost the same as how to create the code posted in the first chapter. In addition, it saves the dynamically created assembly, I have created a class with a field, a constructor with a parameter, an attribute, a constructor with a parameter, and a method. Use a parameter constructor to initialize the field myField, and then call the get_Field method to return the value of the myField field. The console program displays "Hello World !!!"

We will continue to introduce how to dynamically create and use classes and how to create complex methods, especially the generation of intermediate languages (MSIL.

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

Download DEMO

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.