using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Reflection; namespace TestWinform2 { public partial class FrmMain : Form { public FrmMain() { InitializeComponent(); this.StartPosition = FormStartPosition.CenterScreen; IniForm(); } private void IniForm() { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (var item in assemblies) { var name = item.GetName(); if (name.Name == "TestWinform2") { Type[] types = item.GetTypes(); types = types.OrderBy(f => f.FullName, Comparer<string>.Default).ToArray(); int j = 0; foreach (var t in types) { if (t.BaseType == typeof(Form)) { System.Windows.Forms.RadioButton radioButton1 = new RadioButton(); radioButton1.AutoSize = true; radioButton1.Location = new System.Drawing.Point(20, 20 + j * 20); radioButton1.Name = "radioButton" + j; radioButton1.Size = new System.Drawing.Size(95, 16); radioButton1.TabIndex = 0; radioButton1.TabStop = true; radioButton1.Text = t.FullName; radioButton1.Tag = t; radioButton1.UseVisualStyleBackColor = true; radioButton1.MouseDown += new MouseEventHandler(radioButton1_MouseDown); this.Controls.Add(radioButton1); j++; } } } } } void radioButton1_MouseDown(object sender, MouseEventArgs e) { Control control = sender as Control; Type t = control.Tag as Type; Form form = Activator.CreateInstance(t, null, null) as Form; form.FormClosed += new FormClosedEventHandler(form_FormClosed); form.StartPosition = FormStartPosition.CenterScreen; form.Show(); this.Hide(); } void form_FormClosed(object sender, FormClosedEventArgs e) { this.Show(); } } }
我们经常写一些类去测试,比如winform 的但是每次都修改一下Program.cs很麻烦,就这样,写了个反射,每次选一下要测试那个类就测试哪个类,方便了,哇咔咔