C#:当子类从包含这些嵌套类型的基类继承时,按名称获取子类的嵌套类型

问题描述

首先,我完全意识到这有点奇怪,可能不是最佳选择,但我仍在寻找一种方法来实现它:)

我有一个与此类似的课程:

public class Fruit {
  public class Seed { } 
  public class Pit { } 
}

然后我有一个继承的子类:

public class Avocado : Fruit {}

代码的其他地方,我有一个字符串,写着“ Avocado.Pit”,我需要获取确切的Type。

typeof(Fruit).GetnestedTypes()实际上确实包含SeedPit,但是typeof(Avocado).GetnestedTypes()返回空,因为SeedPit位于{{ 1}},而不是在Fruit上(这是预期的:即使Avocado继承自AvocadoFruit的文档也提到来自基本类型的嵌套类是省略)。 如果我手动尝试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;
        }
    }
}