• 反射获取属性


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Reflection;
    
    namespace FalseVerification
    {
        class Program
        {
            static void Main(string[] args)
            {
                Type type = typeof(SomeType);
    
                SomeType st = new SomeType();
                st.Print();
    
                // 正常字段,当然可以修改
                FieldInfo fi = type.GetField("f1", BindingFlags.NonPublic | BindingFlags.Instance);
                fi.SetValue(st, (Int32)fi.GetValue(st) + 1);
    
                // 常量字段,反射也无法修改,如果取消下面语句的注释,执行会出错
                /* 原因说明:常量的值必须在编译时就确定(只能是基元类型),也就是说在定义时就赋值。
                   编译后常量的值是保存在程序集的元数据中,在运行时是不可修改的;
                   而其它字段是存储在动态内存中,在运行时是可修改的。*/
                fi = type.GetField("f2", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
                //fi.SetValue(null, (Int32)fi.GetValue(null) + 1);
    
                // 只读字段,可通过反射方式修改值
                fi = type.GetField("f3", BindingFlags.NonPublic | BindingFlags.Instance);
                fi.SetValue(st, (Int32)fi.GetValue(st) + 1);
    
                // 静态字段,也可修改
                fi = type.GetField("f4", BindingFlags.NonPublic | BindingFlags.Static);
                fi.SetValue(null, (Int32)fi.GetValue(null) + 1);
    
                // 静态只读字段,下面代码不出错,改变了反射字段的值,但类中的字段值并没有被改变
                fi = type.GetField("f5", BindingFlags.NonPublic | BindingFlags.Static);
                fi.SetValue(null, (Int32)fi.GetValue(null) + 1);
                Int32 f5 = (Int32)fi.GetValue(null); // i5 得到值为51
    
                st.Print();
                Console.WriteLine("f5: " + f5.ToString());
                Console.ReadKey();
            }
        }
    
        public class SomeType
        {
            private Int32 f1 = 30;// 私有字段
            private const Int32 f2 = 10;// 私有常量字段
            private readonly Int32 f3 = 20;// 私有只读字段
            private static Int32 f4 = 40;// 私有静态字段
            private static readonly Int32 f5 = 50;// 私有静态只读字段
    
            public void Print()
            {
                Console.WriteLine("f1: " + f1.ToString());
                Console.WriteLine("f2: " + f2.ToString());
                Console.WriteLine("f3: " + f3.ToString());
                Console.WriteLine("f4: " + SomeType.f4.ToString());
                Console.WriteLine("f5: " + SomeType.f5.ToString());
    
                Console.WriteLine();
            }
        }
    }

    转自:http://www.cnblogs.com/Thriving-Country/archive/2009/12/20/1628314.html

  • 相关阅读:
    [Leetcode]@python 89. Gray Code
    [Leetcode]@python 88. Merge Sorted Array.py
    [Leetcode]@python 87. Scramble String.py
    [Leetcode]@python 86. Partition List.py
    [leetcode]@python 85. Maximal Rectangle
    0523BOM
    0522作业星座
    0522dom
    0520
    0519作业
  • 原文地址:https://www.cnblogs.com/Kuleft/p/5310727.html
Copyright © 2020-2023  润新知