ComboBox Elements Displaying Class Names in Solution

I have an open abstract class Clientwith two inheriting classes Customerand TimeWaster.

I created a drop-down menu on C# Windows Formswhich I would like to show in these two names as options: Customer and TimeWaster.

All I can imagine is to create a simple Listone that contains these two expressions, and then bind the list to combobox DataSource:

List<string> clientType = new List<string>()
{
    "Customer",
    "TimeWaster"
};

public frmClientScreen()
{
    cmboxClientType.DataSource = clientType;
}

But this is not supported, because in the future I can add many other classes whose names I would like to display in the drop-down menu.

How to associate the class names in mine Visual Studio Solutionwith the items displayed in the combo box?

+4
2

:

List<string> clientType = new List<string>()
{
    nameof(Customer),
    nameof(TimeWaster)
};

public frmClientScreen()
{
    cmboxClientType.DataSource = clientType;
}

, , , .

:

var listOfBs = (from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
                from assemblyType in domainAssembly.GetTypes()
                where typeof(B).IsAssignableFrom(assemblyType)
                select assemblyType).ToArray();

B .

, , :

var clientTypes = listOfBs.Select(x => x.Name).ToList();
+3

, , , . , :

public static class ReflectionHelper
{
    public static List<T> GetAllNonabstractClassesOf<T>()
    {
        Object[] args = new Object[0];
        return GetAllNonabstractClassesOf<T>(args);
    }

    public static List<T> GetAllNonabstractClassesOf<T>(Object[] args)
    {
        List<T> retVal = new List<T>();
        IEnumerable<object> instances = from t in Assembly.GetExecutingAssembly().GetTypes()
                                        where t.IsSubclassOf(typeof(T)) && !t.IsAbstract
                                        select Activator.CreateInstance(t, args) as object;
        foreach (T instance in instances)
        {
            retVal.Add(instance);
        }
        return retVal;
    }
}

... :

List<myClass> = ReflectionHelper.GetAllNonabstractClassesOf<myClass>();

( , .)

, , , , .

+2

Source: https://habr.com/ru/post/1672577/


All Articles