c Creates the instance code of the same class as the parent class with the class name as a parameter
- 2021-11-30 01:12:18
- OfStack
Here's an example:
Form1, Form2, Form3... are inherited from Form and can be passed through Form f=new Form1 (); Such as Form subclass instance, if too many subclasses, hope to pass a parameter, such as subclass class name can establish an instance, what is the way?
Method 1: Use reflection
string str= "Namespace .Form1(Form2 ... ) " ;
Type t=Type.GetType(str);
Form f=Activator.CreateInstance(t);
In this way, you can achieve what you want. str is a variable. Of course, you need to add a namespace when passing parameters
Method 2: Using generics
T CreateForem<T>() where T : Form, new()// Here's new Used as a constraint
{
return new T();
}
You can then call Form f=CreateForm < Parameter > (); //Parameters are Form1, Form2, Form3, etc.