Get only direct interface instead of all?

前端 未结 6 2280
借酒劲吻你
借酒劲吻你 2020-12-17 09:43

I have a class like the below. GetInterfaces() says

If the current Type represents a type parameter in the definition of a generic type or generic

6条回答
  •  情书的邮戳
    2020-12-17 10:18

    How about this for interface inheritance heirachy?

        public static Map GetTypeInheritance(Type type)
        {
            //get all the interfaces for this type
            var interfaces = type.GetInterfaces();
    
            //get all the interfaces for the ancestor interfaces
            var baseInterfaces = interfaces.SelectMany(i => i.GetInterfaces());
    
            //filter based on only the direct interfaces
            var directInterfaces = interfaces.Where(i => baseInterfaces.All(b => b != i));
    
            Map map = new Map
                {
                    Node = type,
                    Ancestors = directInterfaces.Select(GetTypeInheritance).ToList()
                };
    
            return map;
        }
    
        public class Map
        {
           public Type Node { get; set; }
           public List Ancestors { get; set; }
        }
    

提交回复
热议问题