// Define the dynamic type TypeBuilder tb = module.DefineType("MyDynamicType", TypeAttributes.Public); // Define the method MethodBuilder methodBuilder = tb.DefineMethod("MyDynamicMethod", MethodAttributes.Public, typeof(int), new Type[] { typeof(int), typeof(int) }); // Generate MSIL instructions ILGenerator ilGenerator = methodBuilder.GetILGenerator(); ilGenerator.Emit(OpCodes.Ldarg_1); ilGenerator.Emit(OpCodes.Ldarg_2); ilGenerator.Emit(OpCodes.Add); ilGenerator.Emit(OpCodes.Ret); // Create an instance of the dynamic type and call the method Type dynamicType = tb.CreateType(); object instance = Activator.CreateInstance(dynamicType); int result = (int)dynamicType.GetMethod("MyDynamicMethod").Invoke(instance, new object[] { 1, 2 });
// Define the dynamic type TypeBuilder tb = module.DefineType("MyDynamicType", TypeAttributes.Public); // Define the field FieldBuilder fieldBuilder = tb.DefineField("MyField", typeof(int), FieldAttributes.Public); // Define the getter method MethodBuilder methodBuilder = tb.DefineMethod("get_MyField", MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, typeof(int), Type.EmptyTypes); // Generate MSIL instructions ILGenerator ilGenerator = methodBuilder.GetILGenerator(); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Ldfld, fieldBuilder); ilGenerator.Emit(OpCodes.Ret); // Implement the property PropertyBuilder propertyBuilder = tb.DefineProperty("MyProperty", PropertyAttributes.None, typeof(int), null); propertyBuilder.SetGetMethod(methodBuilder); // Create an instance of the dynamic type and get the property value Type dynamicType = tb.CreateType(); object instance = Activator.CreateInstance(dynamicType); dynamicType.GetField("MyField").SetValue(instance, 42); int result = (int)dynamicType.GetProperty("MyProperty").GetValue(instance);In this example, we define a dynamic type and a public integer field. We then define a getter method for the field and implement a property. Finally, we create an instance of the dynamic type, set the field value, and get the property value. Both of these examples use the System.Reflection.Emit package.