C#的反射机制输出泛型类T及其内嵌List的属性值

做项目的过程中需要动态为自定义强类型的属性赋值,但是有的属性是List,反射回来得到的对象怎么使用index呢?

利用Property的“Count”和"Item"属性可以分别获取下标和对应的对象。

// 需要引用的命名空间
using System.Reflection;
using System;
 
public class Test
{
    public Person person = new Person();
 
    public Test()
    {
        person.country = "china";
        Man man = new Man();
        man.name = "张三";
        man.sex = "男";
        person.manList = new List<Man>();
        person.manList.Add(man);
        PrintMessage<Person>(person);
    }
 
    public static string PrintMessage<T>(T t)
    {
         printMsg.Clear();
         printMsg.Append("\n"+t.ToString()+"\n{\n");
         PrintInternal(t);
         printMsg.Append("}\n");
         return printMsg.ToString();
     }
 
     // 传入需要查询的数据结构体,通过反射打印其所有公共属性
     private static void PrintInternal<T>(T t, string intervalStr = "")
     {
         // 通过泛型类T实例的Type获取所有公共属性
         PropertyInfo[] infos = t.GetType().GetProperties();
         foreach (PropertyInfo info in infos)
         {
             if (info != null)
             {
                 // 判断属性类型是否为泛型类型,如:
                 // typeof(int).IsGenericType --> False
                 // typeof(List<int>).IsGenericType --> True
                 // typeof(Dictionary<int>).IsGenericType --> True
                 if (info.PropertyType.IsGenericType)
                 {
                     // 如List<Man>,返回类名Man
                     string className = info.PropertyType.GetGenericArguments()[0].Name;
                     printMsg.Append("  " + info.Name + ":\n");
                     // 获取该泛型属性值,返回一个列表,如List<Man>;
                     // 因为是反射返回的数据,无法直接转换为List使用,针对这种数据,反射机制对这种属性值提供了
                     // “Count”列表长度、“Item”子元素等属性;
                     object subObj = info.GetValue(t, null);
                     if (subObj != null)
                     {
                         // 获取列表List<Man>长度
                         int count=Convert.ToInt32(subObj.GetType().GetProperty("Count").GetValue(subObj,null));
                         for (int i = 0; i < count; i++)
                         {
                             printMsg.Append(intervalStr +"  {\n");
                             // 获取列表子元素Man,然后子元素Man其实也是一个类,然后递归调用当前方法获取类Man的所有公共属性
                             object item=subObj.GetType().GetProperty("Item").GetValue(subObj,new object[]{i});
                             PrintInternal(item, "  ");
                             printMsg.Append(intervalStr + "  },\n");
                         }
                     }
                   }
                   else {
                       // 属性info,通过info.Name获取属性字段名,通过info.GetValue(t, null)获取值(返回obje类型需要自己转换)
                       printMsg.Append(intervalStr+"  "+info.Name +":"+info.GetValue(t, null).ToString()+"\n");
                   }
              }
         }
     }
}

public class Person{
    public string country;
    public List<Man> manList = new List<Man>();
}

public class Man{
    public string name;
    public string sex;
} 

C#根据属性名称获取泛型的属性值

        /// <summary>
        /// 根据属性名称获取属性值
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="propertyName">属性名称</param>
        /// <returns></returns>
        private object GetPropertyValue(T entity, string propertyName)
        {
            object result = null;
 
            Type entityType = typeof(T);
            try
            {
                PropertyInfo proInfo = entityType.GetProperty(propertyName);
                result = proInfo.GetValue(entity);
            }
            catch (Exception)
            {
 
            }
 
            return result;
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值