c#反射获取类的属性

 主要是使用递归循环出,类的所有属性,其中需要判断属性的类型是否泛型或是否基本类型,尤其注意string类型;如果是字段类型的DateTime或者?类型 请记得调整反射代码。

class Program
    {

        static Type parent = null;
        static List<string> listProperty = new List<string>();
        static void Main(string[] args)
        {

            GetMemberInfoName(typeof(BigHouse).GetProperties());

        }   

public static List<string> GetMemberInfoName(PropertyInfo[] properties)
        {
            string Name = string.Empty;
            foreach (PropertyInfo propertie in properties)
            {
                if (propertie.PropertyType.IsGenericType
                    &&
                    propertie.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
                {
                    parent = propertie.PropertyType.GetGenericArguments().First<Type>();
                    GetMemberInfoName(parent.GetProperties());
                }
                else if (propertie.PropertyType.IsPrimitive == false
                    && propertie.PropertyType.Name != "String")
                {
                    parent = propertie.PropertyType;
                    GetMemberInfoName(propertie.PropertyType.GetProperties());
                }
                else if (propertie.PropertyType.IsPrimitive == true
                    || propertie.PropertyType.Name == "String")
                {
                    if (parent != null)
                        Name = parent.Name + "." + propertie.Name;
                    else
                        Name = propertie.Name;
                    listProperty.Add(Name);
                }
            }
            return listProperty;   
        }

}



类的模型定义: 

public class BigHouse
    {
        /// <summary>
        /// 户主姓名
        / </summary>
        public string Name { get; set; }

        /// <summary>
        /// 所属行政区域
        /// </summary>
        public string Area { get; set; }

        public Address address { get; set; }

        public List<Family> Listfamily { get; set; }
    }
    public class Address
    {
        public string addr { get; set; }
        public string Telephone { get; set; }
    }
    public class Family
    {
        public string Name { get; set; }
        public string Sex { get; set; }
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值