2013-04-12 88 views
1

我有三个项目(项目1,项目2和项目3)都在一个解决方案中。
每个项目都有自己的窗体(C#)。我写我的代码项目3
我要的是列出所有的项目在一个列表框形成名称:
这里是我的代码:从列表框中的三个项目获取表单名称

private void GetFormNames() 
{ 
    foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) 
    { 
     AppDomain.CurrentDomain.Load(a.FullName); 
     foreach (Type t in a.GetTypes()) 
     { 
      if (t.BaseType == typeof(Form)) 
      { 
       Form f = (Form)Activator.CreateInstance(t); 
       string FormText = f.Text; 
       string FormName = f.Name; 
       checkedListBox1.Items.Add("" + FormText + "//" + FormName + ""); 
      } 
     } 
    } 
} 

我'收到此错误:

No parameterless constructor defined for this object.

+6

错误信息是非常明确的IMO .. –

回答

0

当你调用

(Form)Activator.CreateInstance(t); 

由此推测,T级有一个不带参数的构造函数。
你的一个表单不能有无参数的构造函数,这就是你有这个异常的原因。

你可以调用的CreateInstance像

if (t.BaseType == typeof(Form) && t.GetConstructor(Type.EmptyTypes) != null) 

甚至更​​好之前对其进行测试:

if (t.BaseType == typeof(Form)) 
{ 
    var emptyCtor = t.GetConstructor(Type.EmptyTypes); 
    if(emptyCtor != null) 
    { 
     var f = (Form)emptyCtor.Invoke(new object[]{}); 
     string FormText = f.Text; 
     string FormName = f.Name; 
     checkedListBox1.Items.Add("" + FormText + "//" + FormName + ""); 
    } 
} 
+0

就像一个魅力!我有一个额外的澄清,我得到的结果并不令人满意:该函数返回当前项目的确切表单名称,但不适用于其他项目即(在其他项目中,我有form1,form2,form3等..我得到的是“选择窗口”,打印预览等) – WAA

相关问题