In metro, get all inherited classes of an (abstract) class?

自作多情 提交于 2019-12-06 15:41:39
Damir Arh

This should work (based on the code from here):

public IEnumerable<T> GetEnumerableOfType<T>(params object[] constructorArgs) where T : class, IComparable<T>
{
    List<T> objects = new List<T>();
    foreach (Type type in typeof(T).GetTypeInfo().Assembly.ExportedTypes
                                   .Where(myType => myType.GetTypeInfo().IsClass && 
                                                    !myType.GetTypeInfo().IsAbstract && 
                                                    myType.GetTypeInfo().IsSubclassOf(typeof(T))))
    {
        objects.Add((T)Activator.CreateInstance(type, constructorArgs));
    }
    objects.Sort();
    return objects;
}

Basically TypeInfo is now the main class for doing any reflection operations and you can get it by calling GetTypeInfo() on the Type.

Thank you Damir Arh. Your solution is great although it only needs little modification.

One thing I observed is your static method can't be put into MainPage class, or compile-error would happen. Possibly it's because the initializing xaml conflicts with it.

On the other hand, I altered the original code to simpler and useful one with much less run-time error (The line in objects.Add((T)Activator.CreateInstance(type, constructorArgs)); often leads to run-time error in many cases.). The main purpose is just to get all inherited classes after all.

    // GetTypeInfo() returns TypeInfo which comes from the namespace
    using System.Reflection;

    public List<Type> GetEnumerableOfType<T>(params object[] constructorArgs) where T : class
    {
        List<Type> objects = new List<Type>();

        IEnumerable<Type> s = typeof(T).GetTypeInfo().Assembly.ExportedTypes.Where(myType => myType.GetTypeInfo().IsClass &&
                                                         !myType.GetTypeInfo().IsAbstract &&
                                                         myType.GetTypeInfo().IsSubclassOf(typeof(T)));

        foreach (Type type in s)
            objects.Add(type);

        return objects;
    }

And the following is a test sample.

     var list = GetEnumerableOfType<UIElement>();

     foreach (var v in list)
         Debug.WriteLine(v.Name);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!