我一直在试验一个应用程序,它将扫描程序集,检查任何形式的类,然后查看它们有哪些成员。
我用来查询程序集的代码是:
Assembly testAssembly = Assembly.LoadFile(assemblyPath);
Type[] types = testAssembly.GetTypes();
textBox1.Text = "";
foreach (Type type in types)
{
if (type.Name.StartsWith("Form"))
{
textBox1.Text += type.Name + Environment.NewLine;
Type formType = testAssembly.GetType();
Object form = Activator.CreateInstance(formType);
}
}
我正在使用它来查询标准表格:
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace TestForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}
我的问题是,当代码尝试时,Activator.CreateInstance(formType)
我得到一个异常说明:"No parameterless constructor defined for this object."
我还可以从检查 formType 中看到 'DeclaringMethod: 'formType.DeclaringMethod' 抛出了一个类型为 'System.InvalidOperationException' 的异常
我不理解错误消息,因为表单具有标准构造函数,我是否遗漏了一些非常明显的东西?
编辑:type.Name
揭示代码试图实例化的类型Form1
。