C# 如何在任意层次结构中查找最特定的类型
假设我们有一个类型集合:C# 如何在任意层次结构中查找最特定的类型,c#,class,hierarchy,C#,Class,Hierarchy,假设我们有一个类型集合: var types = new[] { typeof(IEnumerable<int>), typeof(ICollection<int>), typeof(Stack<int>), typeof(IList<int>), typeof(int[]) }; 在这种情况下,我想让LeftChildChild和RightChildChild成为您的朋友。在我看来,这是您的朋友。您需要无
var types = new[]
{
typeof(IEnumerable<int>),
typeof(ICollection<int>),
typeof(Stack<int>),
typeof(IList<int>),
typeof(int[])
};
在这种情况下,我想让LeftChildChild和RightChildChild成为您的朋友。在我看来,这是您的朋友。您需要无法从集合中的任何其他类型分配的类型:
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));
}
}
您能显示表示树节点的类型吗?@我正在处理实际类型,请参阅编辑部分。
class Root {}
class LeftChild : Root {}
class RightChild : Root {}
class LeftChildChild : LeftChild {}
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));
}
}