Dynamically load all subclasses of the Assembly inherited from form Using Reflection

Source: Internet
Author: User

Using the reflection of C #, you can easily and quickly create unknown objects of the specified type. For example, you can inherit the class of an interface and inherit the subclass of a base class.

 

Problem scenario:

I create a solution by myself. There are many gadgets in this solution. Every tool is a small form, so I use a mid form to include these forms.

 

In this case, every time I add a small tool, I have to add a button or a menu in the mid form. write in the event to display a form. this type of boring statement.

 

So can the program automatically find the form in the Assembly, the automatic creation button, or the menu.

 

In this way, dynamic creation can be achieved.

 

Solution:

 

Suppose we want to find the class that inherits form from the Assembly.

Key statement:

 

var simpleTypes = from t in Assembly.GetExecutingAssembly().GetTypes()        
where (t.BaseType == typeof(Form) || t.BaseType .BaseType ==typeof(Form)) select t;

This statement is used to find the class that inherits the form or the class that inherits the form from the base class.

(The function is not complete yet, so we can't find too many classes that inherit layers.) So we can find all the form subclasses in the Assembly.

 

How can I create a specified class when clicking?

 

You only need to do this for a class.

Assembly.GetExecutingAssembly().CreateInstance(Class.FullName) as Form

  

All right, we store all the found classes in a dictionary object. The key is the object name, and the value is a delegate.

You can create a form instance by using a keyword in the dictionary search and calling the delegate.

 

The following is all the code.

static class Program    {         /// <summary>        /// The main entry point for the application.        /// </summary>        [STAThread]        static void Main()        {            Application.EnableVisualStyles();            Application.SetCompatibleTextRenderingDefault(false);                        CreateForms();            Application.Run(new FrmMain());                   } private static void CreateForms()        {            var simpleTypes = from t in Assembly.GetExecutingAssembly().GetTypes()                               where (t.BaseType == typeof(Form) || t.BaseType .BaseType ==typeof(Form))                              select t;            foreach ( var simpleType in simpleTypes)            {                _FormTypes.Add(simpleType.Name, simpleType);                _Dictionary.Add(simpleType.Name, (key) => _Assembly.CreateInstance(_FormTypes[key].FullName) as Form);            }                   } private static Dictionary<string, Type> _FormTypes = new Dictionary<string, Type>();        private static Dictionary<string, Func<string, Form>> _Dictionary =            new Dictionary<string, Func<string, Form>>();         static Assembly _Assembly= Assembly.GetExecutingAssembly();             public static Dictionary<string, Func<string, Form>> Forms        {            get { return _Dictionary; }        }}

Call method:

 

Private void createbutton () {foreach (var key in program. forms. keys) {var button = new button {text = key, autosize = true}; button. click + = (sender, e) =>{ var OBJ = sender as button; If (OBJ! = NULL) {var func = program. forms [obj. text]; var form = func (obj. text); form. show () ;}}; flowlayoutpanel2.controls. add (button); // here is a container for storing buttons }}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.