类的属性取值与赋值

        /// <summary>
        /// 从类的属性中获取属性值
        /// </summary>
        /// <param name="p_Instance">属性的容器</param>
        /// <param name="p_PropertyName">属性名</param>
        /// <param name="blThrowException">是否抛出异常</param>
        /// <returns></returns>
        public static object GetPropertyValue(object p_Instance, string p_PropertyName, bool blThrowException)
        {
            Type MyType = p_Instance.GetType();
            PropertyInfo pi = MyType.GetProperty(p_PropertyName);
            if (blThrowException)
            {
                if (pi == null)
                {
                    throw new Exception("在类:[" + MyType.FullName + "] 中不存在属性名为:[" + p_PropertyName + "] 的属性");
                }

                return pi.GetValue(p_Instance, null);
            }

            if (pi == null)
            {
                return null;
            }

            return pi.GetValue(p_Instance, null);
        }
        /// <summary>
        /// 设置类的属性值
        /// </summary>
        /// <param name="p_Instance"></param>
        /// <param name="p_PropertyName"></param>
        /// <param name="p_Value"></param>
        public static void SetPropertyValue(object p_Instance, string p_PropertyName, object p_Value)
        {
            Type MyType = p_Instance.GetType();
            PropertyInfo pi = MyType.GetProperty(p_PropertyName);
            if (pi == null)
            {
                throw new Exception("在类:[" + MyType.FullName + "] 中不存在属性名为:[" + p_PropertyName + "] 的属性");
            }
            if (pi.CanWrite)
            {
                switch (pi.PropertyType.FullName)
                {
                    case "System.Int32":
                        pi.SetValue(p_Instance, StringToInt(ObjectToNullStr(p_Value)), null);
                        break;

                    case "System.DateTime":
                        pi.SetValue(p_Instance, StringToDate(ObjectToNullStr(p_Value)), null);
                        break;
                    default:
                        pi.SetValue(p_Instance, p_Value, null);
                        break;
                }
            }
        }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值