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;
}


C# 中,反射提供了一种动态访问程序运行时信息的方法,包括获取类型、方法、字段等。如果你想使用反射设置类型为类的对象的属性,你可以按照以下步骤操作: 1. **获取类型对象**: 首先,你需要获取你要操作的类的 `Type` 对象。如果你有一个已知的类型名称(如字符串),你可以用 `Type.GetType()` 方法获取。 ```csharp Type myClassType = Type.GetType("Namespace.ClassName"); ``` 2. **获取属性信息**: 使用 `GetProperty()` 方法找到指定名称的属性,如果属性存在,返回 `PropertyInfo` 对象。 ```csharp string attributeName = "PropertyName"; PropertyInfo property = myClassType.GetProperty(attributeName); ``` 3. **检查属性可写性**: 在设置属性之前,确保属性是可以被写的(即它是可赋的)。 ```csharp if (property != null && property.CanWrite) { // ... } else { Console.WriteLine($"无法写入属性 '{attributeName}'"); return; } ``` 4. **获取属性(如果有的话)并设置**: 如果属性是可写的,你可以获取当前设置新的。这里假设属性是 `public` 或者有合适的访问修饰符。 ```csharp object currentValue = property.GetValue(myObjectInstance); // 获取当前 object newValue = ...; // 新的 property.SetValue(myObjectInstance, newValue); // 设置 ``` 5. **处理异常**: 当尝试访问或修改属性时,可能会抛出异常,比如找不到属性或权限不足。记得捕获这些异常。 ```csharp try { // 设置属性 } catch(TargetInvocationException ex) { Console.WriteLine($"错误: {ex.InnerException.Message}"); } catch(Exception ex) { Console.WriteLine($"错误: {ex.Message}"); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值