C# Reflection 執行 Public Method 方法

 
C# Reflection 執行 Public Method 方法
 

   Class2.cs
 
   using System;
   using System.Web.UI.WebControls;
 
   namespace ClassLibrary1
   {
      class Class2
      {
         public TextBox returnTextbox(String InputText)
         {
            TextBox tb = new TextBox();
            tb.Text = InputText.ToString();
            return tb;
         }
 
         public Label returnLabel()
         {
            Label lb = new Label();
            lb.Text = "Reflection Label";
            return lb;
         }
 
         public DropDownList returnDropDownList()
         {
            DropDownList ddl = new DropDownList();
            ddl.Items.Add(new ListItem("Text 1", "Value 1"));
            ddl.Items.Add(new ListItem("Text 2", "Value 2"));
            return ddl;
         }
      }
   }
 

 

   WebForm7.aspx.cs
 
   using System;
   using System.Web.UI;
   using System.Web.UI.WebControls;
   using System.Reflection;
 
   ……
 
   PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
 
   String FP = "C:\\ClassLibrary1\\bin\\Debug\\ClassLibrary1.dll";
 
   Assembly Assem = Assembly.LoadFile(FP);
   Type NType = Assem.GetType("ClassLibrary1.Class2");
   object Inst = Activator.CreateInstance(NType);
 
   TextBox tb = (TextBox)(NType.InvokeMember("returnTextbox",
   BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
   null, Inst, new object[] {"Reflection TextBox"}));
 
   PlaceHolder1.Controls.Add(tb);
 
   Label lbl = (Label)(NType.InvokeMember("returnLabel",
   BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
   null, Inst, new object[] {}));
 
   PlaceHolder1.Controls.Add(lbl);