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

本文关键字:项目 三个 获取 表单 列表 | 更新日期: 2023-09-27 18:08:52

我有三个项目(项目1,项目2和项目3)都在一个解决方案中。
每个项目都有自己的windows窗体(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 + "");
            }
        }
    }
}

我得到这个错误:

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

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

当你调用

(Form)Activator.CreateInstance(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 + "");
    }
}