【问题标题】:How to find all types that used in specific type properties recursively in C# .NET Core?如何在 C# .NET Core 中递归查找特定类型属性中使用的所有类型?
【发布时间】:2017-07-07 19:33:15
【问题描述】:

查看此代码

    public class Person
    {
        public int Id { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public Dictionary<long,float> No {get;set;}
        public DateTime BirthDate { get; set; }
    }

    public class Manager
    {
        public int Id { get; set; }
        public User User { get; set; }
        public List<User> Users { get; set; }
    }

    public class User
    {
        public int Id { get; set; }
        public Person Person { get; set; }
        public List<string> Phones { get; set; }

    }

如何递归查找特定类型属性中使用的所有类型? 例如

GetAllInternalTypes(typeof(Manager))

经理的结果:(经理 => 用户 => 人)

  • int
  • 用户
  • 列表
  • 列表
  • 字符串
  • 日期时间
  • 字典
  • 浮动

我想递归查找特定类型的所有已使用类型。

【问题讨论】:

    标签: c#


    【解决方案1】:

    你的问题有点棘手。因为您只想获取类型的属性,而不是内置于 .Net 库的类型中。例如DictionaryStringDateTimeArray 等,都有自己要排除的属性。幸运的是,有一些方法可以知道 type 是您定义的类型还是来自 System 库。

    How to determine if a object type is a built in system type

    我更喜欢返回PropertyInfo 而不是Type,因为它提供了更多信息,如果您只想获取属性类型,您可以使用 linq 轻松完成。

    var types = properties.OrderBy(p => p.DeclaringType).Select(p => p.PropertyType).Distinct().ToList();
    

    这是简单测试的算法

    static void Main(string[] args)
    {
        var properties = GetTypes(typeof(Manager));
    
        foreach (var propertyInfo in properties)
        {
            Console.WriteLine("{0,-20}{1,-20}{2}", 
                propertyInfo.PropertyType.Name, 
                propertyInfo.DeclaringType?.Name,
                propertyInfo.Name);
        }
    }
    
    public static List<PropertyInfo> GetTypes(Type type)
    {
        if (type.Module.ScopeName == "CommonLanguageRuntimeLibrary" || // prevent getting properties of built-in type
        type == type.DeclaringType)                                    // prevent stack overflow
        {
            return new List<PropertyInfo>();
        }
    
        const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
    
        List<PropertyInfo> result = type
            .GetProperties(flags)
            .SelectMany(p => new[] {p}.Concat(GetTypes(p.PropertyType)))
            .ToList();
    
        return result;
    }
    

    【讨论】:

    • 我有两个问题 1- 不适用于 .NET Core 2- 您的代码无法获取 Dictionary、Array、Tuple、List、Collection 和 ... 的内部类型
    • 内部类型是指泛型类型?可以通过此属性访问它。 type.GenericTypeArguments。例如对于Dictionary&lt;long, float&gt;,它将在数组中给出longfloat 两种类型。如果给定类型不是通用的,则此数组为空。请注意,在我提供的解决方案中,您可以使用 propertyInfo.PropertyType.GenericTypeArguments 访问此属性。
    • 你是什么意思它在 .NET core 2 上不起作用,你得到什么错误?
    • 我知道如何访问任何类型我不知道如何递归编写它!!!看这个例子:Tuple,Tuple>>,DateTime,List>>
    猜你喜欢
    • 2022-11-18
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多