从列表框中的三个项目中获取表单名称

时间:2013-04-12 07:49:31

标签: c# windows forms

我有三个项目(项目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 + "");
            }
        }
    }
}

我收到此错误:

  

没有为此对象定义无参数构造函数。

1 个答案:

答案 0 :(得分: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 + "");
    }
}