简体   繁体   中英

How to instantiate a descendant UserControl?

Here is the scenario. I have a bunch of UserControls that all inherit from MyBaseControl. I would like to instantiate a UserControl based on its name. For instance:

void foo(string NameOfControl) {
    MyBaseControl ctl = null;        
    ctl = CreateObject(NameOfControl);  // I am making stuff up here, 
                                        // CreateObject does not exist
}

How do i instantiate this UserControl based on its name. I could have a gigantic switch statement and that smells bad. All the UserControls, including their Base class, are in the same project and all have the same namespace.

The best way to do this would be to load the type via reflection. Since they are all in the same assembly/namespace, you can do this. Otherwise, you'd have to load the assembly separately. Also, it assumes an empty constructor.

MyBaseControl ctl = null;
ctl = (MyBaseControl) typeof(MyBaseControl).assembly.GetType(NameOfControl).GetConstructor(new Type[0]).Invoke(new object[0]);

If the constructor isn't an empty one, change the type/object arrays.

    void foo(string NameOfControl)
    {
        MyBaseControl ctl = null;
        ctl = (MyBaseControl) Assembly.GetExecutingAssembly().CreateInstance(typeof(MyBaseControl).Namespace + "." + NameOfControl);
    }

Above assumes that each of your derived control class as a default parameter-less constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM