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);
                        }
                      
                    }
                }
               
            }
  • 相关阅读:
    Day8 类的继承
    Day7 访问权限
    javascript性能优化
    JavaScript 基础:Babel 转译 class 过程窥探
    HTML5之新增的元素和废除的元素 (声明:内容节选自《HTML 5从入门到精通》)
    谈起音视频,前端能做些什么
    Safari不能保存session的处理方法
    一篇关于BEM命名规范
    H5新人福音~零配置搭建现代化的前端工程
    2018年,最经典的26个JavaScript面试题和答案!
  • 原文地址:https://www.cnblogs.com/muzizongheng/p/3169039.html
Copyright © 2011-2022 走看看