1. 程式人生 > >C# Reflection 獲取私有欄位、方法

C# Reflection 獲取私有欄位、方法

使用反射,可以獲取其他類中的私有欄位、屬性、私有方法等。

測試使用的類如下:

public class Model
    {
        /// <summary>
        /// 欄位
        /// </summary>
        public string _name = "Reflection";
        private int _id;
        protected bool _isAdmin = true;


        /// <summary>
        /// 屬性
        /// </summary>
        public string Name 
        {
            get { return this._name; }
            set { this._name = value; }
        }

        public int Id 
        {
            get { return this._id; }
            set{this._id=value;}
        }
        protected bool isAdmin { get; set; }

        /// <summary>
        /// 方法
        /// </summary>
        private int PrivateMethod(int i, int j)
        {
            return (i +j)* 2;
        }
        protected void ProtectedMethod()
        { 
        }
        /// <summary>
        /// 構造方法
        /// </summary>
        public Model()
        {
            this.Id = 0;
        }
    }

測試程式碼如下:
static void Main(string[] args)
        {
            var model = new Model();

            Type t = typeof(Model);
            t.GetProperty("Id").SetValue(model, 111, null);

            //field 欄位: 私有欄位
            var prop = model.GetType().GetField("_id", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            prop.SetValue(model, 13);

            //property 屬性
            PropertyInfo property = model.GetType().GetProperty("Name");
            property.SetValue(model, "test",null);

            //method 私有方法
            MethodInfo method = model.GetType().GetMethod("Android", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            //引數
            object[] obj = new object[2] { 1, 3 };
            object returnVal = method.Invoke(model, obj);

            Console.ReadKey();
        }