创建表单实例时出现反射错误
我一直在尝试一个应用程序,该应用程序将扫描程序集,检查是否有任何表单类,然后查看它们拥有哪些成员。
我用来查询程序集的代码是:
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)
时,我收到一个异常,指出: “没有为此对象定义无参数构造函数。”
我还可以通过检查 formType 看到 'DeclaringMethod: 'formType.DeclaringMethod' 抛出了类型 'System.InvalidOperationException'' 的异常
我不明白错误消息,因为表单有一个标准构造函数,我是否遗漏了一些非常明显的东西?
编辑: type.Name
显示代码尝试实例化为 Form1
的类型。
I've been experimenting with an application that will scan an assembly, check for any classes that are forms and then see what members they have.
The code I'm using to query the assemblies is:
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);
}
}
I'm using this to query a standard form:
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace TestForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}
My problem is that when the code tries Activator.CreateInstance(formType)
I get an exception stating: "No parameterless constructor defined for this object."
I can also see from checking formType that 'DeclaringMethod: 'formType.DeclaringMethod' threw an exception of type 'System.InvalidOperationException''
I don't understand the error message as the form has a standard constructor, am I missing something really obvious?
EDIT : type.Name
reveals the type that the code is trying to instantiate as being Form1
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在尝试创建 Assembly 的实例,而不是您的表单的实例:
您应该这样做:
顺便说一句,我不会使用类的名称来检查它是否是从 Form 派生的,您可以使用 IsSubclassOf:
You are trying to create an instance of Assembly, not of your form:
You should do:
BTW, I wouldn't use the name of the class to check if it is derived from Form, you can use IsSubclassOf:
对象形式 = Activator.CreateInstance(类型);
Object form = Activator.CreateInstance(type);