C# 通过反射获取/设置属性值

//具体类
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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值