C# 通过反射机制获取属性和属性值,以及给对象属性赋值

1、通过反射机制获取对象属性和属性值,以及给对象属性赋值。

2、反射工具代码

 /// <summary>
    /// 反射工具
    /// </summary>
    public static class ReflexHelper
    {
        #region 对象相关 
        /// <summary>
        /// 取对象属性值
        /// </summary>
        /// <param name="FieldName"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetModelValue(string FieldName, object obj)
        {
            try
            {
                Type Ts = obj.GetType();
                object o = Ts.GetProperty(FieldName).GetValue(obj, null);
                if (null == o)
                    return null;
                string Value = Convert.ToString(o);
                if (string.IsNullOrEmpty(Value))
                    return null;
                return Value;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return null;
        }

        /// <summary>
        /// 设置对象属性值
        /// </summary>
        /// <param name="FieldName"></param>
        /// <param name="Value"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool SetModelValue(string FieldName, string Value, object obj)
        {
            try
            {
                Type Ts = obj.GetType();
                object v = Convert.ChangeType(Value, Ts.GetProperty(FieldName).PropertyType);
                Ts.GetProperty(FieldName).SetValue(obj, v, null);
                return true;
            }
            catch (Exception ex)
            {
               throw ex;
            }
            return false;
        }
        #endregion

       
    }

3、简单对象

   public class User
    {
        public int Id { get; set; }

        public string UserName { get; set; }
    }

4、测试:

    static void Main(string[] args)
        {
            User user = new User
            {
                Id = 100,
                UserName = "Ace"
            };
            //获取属性值
            var id = ReflexHelper.GetModelValue("Id",user);

            //设置属性值
            User setUser = new User();
            ReflexHelper.SetModelValue("UserName", "Test", setUser);

            Console.ReadLine();
        }

 

posted @ 2022-08-24 16:56  大空白纸  阅读(1605)  评论(0编辑  收藏  举报