C#按属性名反射获取和设置对象属性值

时间:2022-03-13 05:15:35

using System;
using System.Collections.Generic;
using System.Reflection;

namespace test
{
    public class MyClass
    {
        public static void Main()
        {
            Product p=new Product();
            //
            p.Pkid=12;
            p.ProductName="安全气囊";
            Console.WriteLine(p.ShowMe());
            //获取
            PropertyInfo propertyPkid=typeof(Product).GetProperty("Pkid");
            Console.WriteLine(propertyPkid.GetValue(p,null));//获取1
            PropertyInfo propertyProductName=typeof(Product).GetProperty("ProductName");
            Console.WriteLine(propertyProductName.GetValue(p,null));//获取2
            //设置
            PropertyInfo propertyPkid_2=typeof(Product).GetProperty("Pkid");
            propertyPkid_2.SetValue(p,99,null);//设置1
            PropertyInfo propertyProductName_2=typeof(Product).GetProperty("ProductName");
            propertyProductName_2.SetValue(p,"七扭八歪",null);//设置2
            Console.WriteLine(p.ShowMe());
            //
            Console.ReadLine();
        }
    }
    /// <summary>
    ///
    /// </summary>
    public class Product
    {
        public int Pkid
        {
            get{return _pkid;}
            set{_pkid = value;}
        }
        private int _pkid;
        public string ProductName
        {
            get{return _productName;}
            set{_productName=value;}
        }
        private string _productName;
        public string ShowMe()
        {
            return string.Format("Pkid={0}\tProductName={1}",Pkid,ProductName);
        }
    }   
}

转载链接:点击打开链接

 

自己提取了公共方法:

        #region 根据属性名称获取值
        /// <summary>
        /// 根据属性名称获取值
        /// </summary>
        /// <param name="obj">对象实例</param>
        /// <param name="strAttribute">属性名</param>
        /// <returns>object</returns>
        private static object GetValueByStrAttribute(object obj, string strAttribute)
        {
            System.Reflection.PropertyInfo propertyInfoName = (obj.GetType()).GetProperty(strAttribute);
            return propertyInfoName.GetValue(obj, null);
        }
        #endregion

        #region 根据属性名称设置值
        /// <summary>
        /// 根据属性名称设置值
        /// </summary>
        /// <param name="obj">对象实例</param>
        /// <param name="strAttribute">属性名</param>
        /// <param name="value">值</param>
        private static void SetValueByStrAttribute(object obj, string strAttribute, object value)
        {
            System.Reflection.PropertyInfo propertyInfoName = (obj.GetType()).GetProperty(strAttribute);
            propertyInfoName.SetValue(obj, value, null);
        }
        #endregion