mercredi 3 avril 2019

C# Reflection - How to reload a class on runtime?

Currently I am working on a project in C# where I have to implement reflection. I have created a WPF application with a GUI. This GUI contains a combobox which contains all the classnames that implement a specific interface. The classes with the displayed classnames live in the same solution. Next to the combobox is a button to refresh the content in the combobox. However, when I run my application, modify a classname that implements the interface, and click on that refresh button the changes don't show up in the combobox. For example, when I change a classname it should display the new classname in stead of the old one.

I have extracted this part of my project to test it in an empty console application. Here I have an interface that is implemented by the classes QuickSortAlgorithm, DynamicSortAlgorithm and MergeSortAlgorithm. Next I wrote the following, straight forward code, in my main class.

    public static List<string> AlgoList = new List<string>();

    static void Main(string[] args) {
        RefreshAlgorithms();
        Print();

        Console.WriteLine("\nChange a classname and press a key \n");
        Console.ReadKey();

        Print();

        Console.WriteLine("\nPress a key to exit the program \n");
        Console.ReadKey();
    }

    private static void RefreshAlgorithms() {
        AlgoList.Clear();
        Type AlgorithmTypes = typeof(IAlgorithms);
        foreach (var type in Assembly.GetCallingAssembly().GetTypes()) {
            if (AlgorithmTypes.IsAssignableFrom(type) && (type != AlgorithmTypes)) {
                AlgoList.Add(type.Name);
            }
        }
    }

    private static void Print() {
        Console.WriteLine("Algorithm classes:");
        foreach (var Algo in AlgoList) {
            Console.WriteLine(Algo);
        }
    }

When I run the application is see the classnames QuickSortAlgorithm, DynamicSortAlgorithm and MergeSortAlgorithm printed. However if I change the name of the, for example, QuickSortAlgorithm class to QuickSortAlgorithmmmmm I would expect it to print QuickSortAlgorithmmmmm once I press a key. However this is not the case and the name QuickSortAlgorithm is still being displayed.

I get the feeling that I overlook something in the concept of reflection. Can this even be done after building the solution? If I understood correctly this concept makes it possible to implement changes on runtime. I know that it will make my application much slower but I'm really eager to learn more about this concept. If one can explain me what I'm doing wrong I would be very happy.





Aucun commentaire:

Enregistrer un commentaire