C#利用反射获取与设置对象的属性值

代码包含两个方法:GetPropertyValue 和 SetPropertyValue。这两个方法都是泛型方法,可以用于获取和设置对象的属性值。

在 GetPropertyValue 方法中:

  1. 首先获取传入对象的类型。
  2. 查找指定属性名称的属性,并忽略大小写。
  3. 如果找不到属性,则返回空字符串。
  4. 获取该属性的值,并将其转换为字符串返回。

在 SetPropertyValue 方法中:

  1. 获取传入对象的类型。
  2. 使用指定属性名称获取属性。
  3. 如果找不到属性,则返回空字符串。
  4. 使用 SetValue 方法设置属性的值为传入的字段值。
     public string GetPropertyValue<T>(T model, string fieldName)
        {
            Type type = typeof(T);//或者 Type type = model.GetType();
    
            PropertyInfo property = type.GetProperties()
                    .FirstOrDefault(p => string.Equals(p.Name, fieldName, StringComparison.OrdinalIgnoreCase));
            //PropertyInfo property = type.GetProperty(field, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
    
    
            if (property == null) return string.Empty;
    
            object fieldValue = property.GetValue(model, null);
    
            if (fieldValue == null) return string.Empty;
    
            return fieldValue.ToString();
        }
    
        public T SetPropertyValue<T>(T model, string fieldName, object fieldValue)
        {
    
            model.GetType().GetProperty(fieldName).SetValue(model, fieldValue);
            Type type = typeof(T);//或者 Type type = model.GetType();
    
            PropertyInfo property = type.GetProperties()
                    .FirstOrDefault(p => string.Equals(p.Name, fieldName, StringComparison.OrdinalIgnoreCase));
              //PropertyInfo property = type.GetProperty(field, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
    
    
            if (property == null) return string.Empty;
    
            object fieldValue = property.SetValue(model, fieldValue);
    
            if (fieldValue == null) return string.Empty;
    
            return fieldValue.ToString();
        }
    

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值