//具体类
public class A
{
public int Property1 { get; set; }
}
A aa = new A();
Type type = aa.GetType();
PropertyInfo propertyInfo = type.GetProperty("Property1");
propertyInfo.SetValue(aa, 5, null);
int value = (int)propertyInfo.GetValue(aa, null);
//简写
aa.GetType().GetProperty("Property1").SetValue(aa, 5, null);
object value = aa.GetType().GetProperty("Property1").GetValue(aa., null);
//泛型类
Type type = typeof(T);
T t = (T)Activator.CreateInstance(type, new object[] { });
//反射效率低,能不用就不用
//常规做法 虽然每个实体类都要写,但是效率高
public static IList<AA> GetData(SqlDataReader dr)
{
IList<AA> list = new List<AA>();
while (dr.Read())
{
AA aa = new AA();
aa.p1 = dr.GetString(1);
aa.p2 = dr.GetString(2);
aa.p3 = dr.GetString(3);
......
list.Add(aa);
}
return list;
}
//反射做法 虽然通用,但是效率低
public static IList<T> GetData(SqlDataReader dr)
{
IList<T> list = new List<T>();
Type type = typeof(T);
PropertyInfo[] properties = type.GetProperties();
while (dr.Read())
{
T t = Activator.CreateInstance<T>();
for (int i = 0; i < properties.Length; i++)
{
properties[i].SetValue(t, dr[i + 1], null);
}
list.Add(t);
}
return list;
}