如何在任意层次结构中查找最具体的类型(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)); } }更多推荐
发布评论