如何在任意层次结构中查找最具体的类型(How to find the most specific types in an arbitrary hierarchy)

编程入门 行业动态 更新时间:2024-10-12 05:52:48
如何在任意层次结构中查找最具体的类型(How to find the most specific types in an arbitrary hierarchy)

假设我们有一系列类型:

var types = new[] { typeof(IEnumerable<int>), typeof(ICollection<int>), typeof(Stack<int>), typeof(IList<int>), typeof(int[]) };

编辑

在我的问题中,我正在处理相互派生的实际类型,创建一个树。 例如,我可以:

class Root {} class LeftChild : Root {} class RightChild : Root {} class LeftChildChild : LeftChild {}

Edit

In my problem, I am dealing with actual types that derive from each other, creating a tree. For example, I can have:

class Root {} class LeftChild : Root {} class RightChild : Root {} class LeftChildChild : LeftChild {}

In which case I would like to yield LeftChildChild and RightChild.

最满意答案

在我看来, Type.IsAssignableFrom是你的朋友。 您需要的类型不能从集合中的任何其他类型分配:

using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var types = new[] { typeof(IEnumerable<int>), typeof(ICollection<int>), typeof(Stack<int>), typeof(IList<int>), typeof(int[]) }; var leaves = types.Where(candidate => !types.Any(t => t != candidate && candidate.IsAssignableFrom(t))); Console.WriteLine(string.Join(Environment.NewLine, leaves)); } }

It seems to me that Type.IsAssignableFrom is your friend here. You want types that aren't assignable from any of the other types in the set:

using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var types = new[] { typeof(IEnumerable<int>), typeof(ICollection<int>), typeof(Stack<int>), typeof(IList<int>), typeof(int[]) }; var leaves = types.Where(candidate => !types.Any(t => t != candidate && candidate.IsAssignableFrom(t))); Console.WriteLine(string.Join(Environment.NewLine, leaves)); } }

更多推荐

本文发布于:2023-07-06 01:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1044342.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:层次   类型   结构   如何在   find

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!