• 利用反射拿到并递归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);
                        }
                      
                    }
                }
               
            }
  • 相关阅读:
    ADexplorer
    Ldap登陆AD(Active Directory)进行认证的Java示例
    通过LDAP验证Active Directory服务
    APACHE + LDAP 的权限认证配置方法
    How to authenticate a user by uid and password?
    js汉字与拼音互转终极方案,附简单的JS拼音输入法【转】
    给MySQL增加mysql-udf-http和mysql-udf-json自定义函数,让MySQL有调用http接口和查询直接回JSON的能力
    CentOS6.7安装RabbitMQ3.6.5
    CentOS利用inotify+rsync实现文件同步
    CentOS两台服务器利用scp拷贝文件
  • 原文地址:https://www.cnblogs.com/muzizongheng/p/3169039.html
Copyright © 2020-2023  润新知