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

。_饼干妹妹 提交于 2020-01-03 04:20:10

问题


I got stuck when trying to get all inherited classes in metro. The WinRT API is different from .net framework, so both the solutions (solution1 and solution2) don't work.

Any code or tool solution is appreciated.

I'm still trying. I will put my solution here if success.


回答1:


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.




回答2:


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);


来源:https://stackoverflow.com/questions/13373000/in-metro-get-all-inherited-classes-of-an-abstract-class

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