Hi All,
I'm learning how to write C# using reflection, but don't know how to
code using reflection
this.Controls.Add(this.label1);
Could anyone help, Thank in advance.
xxx=============================================== =======================
using System;
using System.Reflection;
using System.Reflection.Emit; // To emit MSIL
using System.Threading; // To get Current AppDomain
using System.IO;
public class HelloWorld
{
static void Main()
{
// public class Form1:System.Windows.Forms.Form{Form1(){}}
// Form1 s= new Form1();
Assembly WinFormasm = Assembly.Load("System.Windows.Forms,
Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
Type WinForm = WinFormasm.GetType("System.Windows.Forms.Form");
// Create a simple name for the assembly.
AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = "Form1Assembly";
// Create the dynamic assembly.
AssemblyBuilder assembly =
Thread.GetDomain().DefineDynamicAssembly(assemblyN ame,
AssemblyBuilderAccess.Run);
// Create a dynamic module.
ModuleBuilder module = assembly.DefineDynamicModule("Form1Module");
// Define a public class named "Form1Class" in the assembly.
TypeBuilder Form1Class = module.DefineType("Form1",
TypeAttributes.Public, WinForm);
// Create the constructor.
Type[] constructorArgs = null;
ConstructorBuilder constructor =
Form1Class.DefineConstructor(MethodAttributes.Publ ic,
CallingConventions.Standard, constructorArgs);
// Generate IL for the method. The constructor calls its superclass
// constructor. The constructor stores its argument in the private field.
ILGenerator constructorIL = constructor.GetILGenerator();
constructorIL.Emit(OpCodes.Ldarg_0);
ConstructorInfo superConstructor = WinForm.GetConstructor(new Type[0]);
constructorIL.Emit(OpCodes.Call, superConstructor);
constructorIL.Emit(OpCodes.Ret);
// the class CodeGenClass.
Type Form1 = Form1Class.CreateType();
object s= Activator.CreateInstance (Form1);
object label1= Activator.CreateInstance
(WinFormasm.GetType("System.Windows.Forms.Label")) ;
object textBox1= Activator.CreateInstance
(WinFormasm.GetType("System.Windows.Forms.TextBox" ));
object button1= Activator.CreateInstance
(WinFormasm.GetType("System.Windows.Forms.Button") );
/* please show how to implement these 3 lines using reflection.
this.Controls.Add(this.label1);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox1);
*/
Form1.GetProperty("Text", typeof(string)).SetValue(s, "Hello
World",null);
Console.WriteLine("value {0}",Form1.GetProperty("Text",
typeof(string)).GetValue(s, null));
// Application.Run(New Form1);
Type WinApplication =
WinFormasm.GetType("System.Windows.Forms.Applicati on");
MethodInfo method = WinApplication.GetMethod("Run", new
Type[]{WinForm});
object result = method.Invoke(null, new object[]{s});
}
}