Reflection error when creating an instance of a form
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 const开发者_Python百科ructor, am I missing something really obvious?
EDIT : type.Name
reveals the type that the code is trying to instantiate as being Form1
.
You are trying to create an instance of Assembly, not of your form:
Type formType = testAssembly.GetType();
Object form = Activator.CreateInstance(formType);
You should do:
Object form = Activator.CreateInstance(type);
BTW, I wouldn't use the name of the class to check if it is derived from Form, you can use IsSubclassOf:
type.IsSubclassOf(typeof(Form));
Object form = Activator.CreateInstance(type);
精彩评论