问题描述
首先,我完全意识到这有点奇怪,可能不是最佳选择,但我仍在寻找一种方法来实现它:)
public class Fruit {
public class Seed { }
public class Pit { }
}
public class Avocado : Fruit {}
在代码的其他地方,我有一个字符串,写着“ Avocado.Pit”,我需要获取确切的Type。
typeof(Fruit).GetnestedTypes()
实际上确实包含Seed
和Pit
,但是typeof(Avocado).GetnestedTypes()
返回空,因为Seed
和Pit
位于{{ 1}},而不是在Fruit
上(这是预期的:即使Avocado
继承自Avocado
,Fruit
的文档也提到来自基本类型的嵌套类是省略)。
如果我手动尝试GetnestedTypes()
或new Avocado.Pit();
,它确实可以按预期工作,因此似乎应该可行。
那我该怎么做:
SomeGenericmethod<Avocado.Pit>();
我希望真正的方法需要更多的帮助,但这很好。这可能吗?非常感谢!
解决方法
下面的程序将打印您的嵌套类型:
TypeExample.Avocado + Peel
TypeExample.Fruit + Seed
TypeExample.Fruit + Pit
TypeExample.Fruit + Seed + InnerSeed
using System;
using System.Collections.Generic;
using System.Linq;
namespace TypeExample
{
class Program
{
static void Main(string[] args)
{
var type = typeof(Avocado);
var types = type.RetrieveNestedTypes();
foreach (var innerType in types)
{
Console.WriteLine(innerType.FullName);
}
Console.ReadKey();
}
}
public class Fruit
{
public class Seed
{
public class InnerSeed { }
}
public class Pit { }
}
public class Avocado : Fruit
{
public class Peel { }
}
public static class TypeHelper
{
public static List<Type> RetrieveNestedTypes(this Type type)
{
List<Type> list = new List<Type>();
list.AddRange(RetrieveNestedInnerTypes(type));
return list;
}
private static List<Type> RetrieveNestedInnerTypes(Type type)
{
var types = type.GetNestedTypes().ToList();
foreach (Type innerType in types.ToList())
{
types.AddRange(RetrieveNestedInnerTypes(innerType));
}
var basetype = type.BaseType;
if (basetype != null)
{
types.AddRange(RetrieveNestedInnerTypes(basetype));
}
return types;
}
}
}