做项目的过程中需要动态为自定义强类型的属性赋值,但是有的属性是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;
}