I want to convert the string Form name to Winform Object to show the form.In project the string form name is getting from database 开发者_JAVA技巧header table and its constructor is get from its detail table.
Here is the table structure
*HEADER TABLE*
ID,Name
*DETAIL TABLE*
ID,Constructor_Name,Constructor_Value
Generally. the DB and UI are at such opposite ends that I would recommend don't store the actual winform name, but store some string token / enumeration instead, and just use a switch:
switch(formName) {
case "OrderInfo": return new OrderInfoForm(ctorValue);
case "CustomerSearch": return new CustomerSearchForm();
// etc
}
in all seriousness, the above is not usually much of a maintenance overhead, and the static typing makes it hard to get much wrong. And it will still work when you refactor or switch to a different UI implementation.
However, you can use reflection. If you have an assembly-qualified name, then:
Type type = Type.GetType(name);
otherwise, if just namespace-qualified, you should ideally obtain the Assembly
first:
Assembly asm = typeof(SomeTypeInTheSameAssembly).Assembly;
Type type = asm.GetType(name);
Then simply:
Form form = (Form)Activator.CreateInstance(type, ctorValues);
You'll need to use reflection to do this.
Use Type.GetType(string)
to get the Type
object from its name, and then either call Activator.CreateInstance()
to create an instance, or fetch a particular constructor with Type.GetConstructor()
and then call ConstructorInfo.Invoke()
to invoke it.
Either way, you'll then probably want to just cast the newly created object to Form
in order to display it.
One thing to consider is what your constructor parameter types are, and how to associate each constructor parameter with the specific row in the table. Do your forms have multiple parameters? Are there any complex values, or are they all strings, ints etc?
精彩评论