mercredi 18 juillet 2018

How can i get all sub classes in a class using reflection in C# [duplicate]

This question already has an answer here:

how to get all sub classes under main class

I want to get class structure using Reflection and show that in a TreeView. that is what i did but it's dosen't works!! Here is just a Test class to explain what i mean. can sombody show me a simple way to do it?

   // Main Class
    public class GetOrders
    {
       // Sub Class Level 1
        public class OpenOrders
        {
            // Sub Class Level 2
            public class AllOrders
            {
            // Some Codes
            }

            // Sub Class Level 2
            public class OrdersTransportedTo
            {
                // Sub Class Level 3
                public class Customer1
                {
                // Some Codes
                }

                // Sub Class Level 3
                public class Customer2
                {
                // Some Codes
                }
            }
        }
        // Sub Class Level 1
        public class NotScheduled
        {
            // Sub Class Level 2
            public class AllOrders
            {
            // Some Codes
            }
        }
        .
        .
        .
    }

I tried this Code, however its doesn't works

 // My Method to get Sub Classes
 private void GetClassTree()
    {
        //Create A Instance from Class
        GetOrders obj = new GetOrders();

        //Add main class to TreeView
        treeView1.Nodes.Add(obj.GetType().Name, obj.GetType().Name);

        // Get all classes inside the created instance of main class
        foreach (MemberInfo Item in obj.GetType().GetMembers())
        {
            // Add sub classes in first level 
            treeView1.Nodes[obj.GetType().Name].Nodes.Add(Item.Name, Item.Name);
            foreach (MemberInfo SubItem in Item.GetType().GetMembers())
            {
                // Add sub classes in second level 
                treeView1.Nodes[Item.Name].Nodes.Add(Item.Name);

                // Check if there is sub class in third level
                if (SubItem.GetType().GetMembers() != null)
                {
                    foreach (MemberInfo SubIteml1 in SubItem.GetType().GetMembers()){

                     // Add sub classes in third level  
                     treeView1.Nodes[SubItem.Name].Nodes.Add(SubIteml1.Name);
                    }
                }
            }
        }
    }





Aucun commentaire:

Enregistrer un commentaire