zoukankan      html  css  js  c++  java
  • 利用反射拿到并递归C#类中的各个字段名字及类型

       以下方法实现了遍历一个class中所有的字段, 并且递归遍历sub class。

     private StringBuilder _properties = new StringBuilder();

            public MainView()
            {
                TraversalProperties(typeof(StudyInfoModel));

                File.WriteAllText("Properties.txt", _properties.ToString());
            }


    private void TraversalProperties(Type classTemplate)
            {
                if (null == classTemplate)
                {
                    return;
                }
               
                foreach (PropertyInfo pi in
                    classTemplate.GetProperties(BindingFlags.Public | BindingFlags.Instance| BindingFlags.DeclaredOnly))
                {
                    PropertyInfo needUpdateValue = classTemplate.GetProperty(pi.Name);

                    if (needUpdateValue.PropertyType.Equals(classTemplate))
                    {
                        return;
                    }

                    if (needUpdateValue.PropertyType.IsArray
                        || (needUpdateValue.PropertyType.IsClass
                            && !needUpdateValue.PropertyType.IsGenericType
                            && !needUpdateValue.PropertyType.Equals(typeof(String))
                            && !needUpdateValue.PropertyType.IsValueType
                            )
                        )
                    {
                        TraversalProperties(needUpdateValue.PropertyType);
                    }
                    else if (needUpdateValue.PropertyType.IsGenericType
                        &&  needUpdateValue.PropertyType.GetGenericTypeDefinition()== typeof(ObservableCollection<>))
                    {
                        TraversalProperties(needUpdateValue.PropertyType.GetGenericArguments()[0]);
                    }
                    else
                    {
                        if (classTemplate.Name.Contains("StudyInfoModel"))
                        {
                            _properties.AppendFormat(""{0}", ", needUpdateValue.Name);
                        }
                        else
                        {
                            _properties.AppendFormat(""{0}_{1}", ", classTemplate.Name.Replace("InfoModel", ""), needUpdateValue.Name);
                        }
                      
                    }
                }
               
            }
  • 相关阅读:
    对多分类采用10折交叉验证评估实验结果
    对二分类采用10折交叉验证评估实验结果
    对回归采用10折交叉验证评估实验结果
    在多分类任务实验中 用torch.nn实现 𝑳𝟐 正则化
    在多分类任务实验中手动实现 使用 𝑳𝟐 正则化
    随学随用的python-note
    Scala类型参数中协变(+)、逆变(-)、类型上界(<:)和类型下界(>:)的使用
    Scala写排序可以说是简洁又明了
    Scala中的apply实战详解
    Scala单例对象、伴生对象实战详解
  • 原文地址:https://www.cnblogs.com/muzizongheng/p/3169039.html
Copyright © 2011-2022 走看看