//动态属性获取PropertyInfo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Test> list = new List<Test>() { new Test(){Name="zfl",Age=25},new Test(){Name="lcj",Age = 25}};
list.ForEach(t =>
// Console.WriteLine("Name:"+t.Name+",Age="+t.Age)
Write(t)
);
Console.Read();
}
static void Write(object a)
{
PropertyInfo[] pros = a.GetType().GetProperties();//1.获取所有公共的属性集合
int i = 0;
foreach(PropertyInfo pro in pros)
{
object obj = pro.GetValue(a, null);//2.获取值
//pro.Name ; //获取属性的名称
//pro.PropertyType; //获取属性的数据类型如(System.String)
var v = obj; //用var 定义变量,进行数据的动态接收,var的类型根据obj 的GetType()类型来决定
Console.WriteLine( v);
i++;
}
}
}
class Test
{
public String Name { get; set; }
public int Age { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Test> list = new List<Test>() { new Test(){Name="zfl",Age=25},new Test(){Name="lcj",Age = 25}};
list.ForEach(t =>
// Console.WriteLine("Name:"+t.Name+",Age="+t.Age)
Write(t)
);
Console.Read();
}
static void Write(object a)
{
PropertyInfo[] pros = a.GetType().GetProperties();//1.获取所有公共的属性集合
int i = 0;
foreach(PropertyInfo pro in pros)
{
object obj = pro.GetValue(a, null);//2.获取值
//pro.Name ; //获取属性的名称
//pro.PropertyType; //获取属性的数据类型如(System.String)
var v = obj; //用var 定义变量,进行数据的动态接收,var的类型根据obj 的GetType()类型来决定
Console.WriteLine( v);
i++;
}
}
}
class Test
{
public String Name { get; set; }
public int Age { get; set; }
}
}