C# 反射修改私有静态成员变量 反射获取修改类中的属性值

	//动态链接库中ClsPublic类有一变量 private static string key="1111";
//下面通过反射的技术修改和获取值
//设置key
public static void updatePalmKey(string key = "test") { BindingFlags flag = BindingFlags.Static | BindingFlags.NonPublic; FieldInfo f_key = typeof(ClsPublic).GetField("key", flag); f_key.SetValue(new ClsPublic(), key); } /// /// 获取key /// /// public static string getPalmKey() { BindingFlags flag = BindingFlags.Static | BindingFlags.NonPublic; FieldInfo f_key = typeof(ClsPublic).GetField("key", flag); object o = f_key.GetValue(new ClsPublic()); return o.ToString(); }
 
  
	//反射获取修改类中的属性
	class Test
	{
		public string StrTest {get; set;};
	}
        /// 
        /// 获取修改类中的属性
        /// 
        /// 
        public void GetAndSetProperty()
        {
		Test t = new Test();
		PropertyInfo p=t.GetType().GetProperty("StrTest");
                p.SetValue(p,"test");
        }



        /// 
        /// 获取key
        /// 
        /// 
        public static string getPalmKey()
        {
            BindingFlags flag = BindingFlags.Static | BindingFlags.NonPublic;
            FieldInfo f_key = typeof(ClsPublic).GetField("key", flag);
            object o = f_key.GetValue(new ClsPublic());
            return o.ToString();
        }

你可能感兴趣的:(反射)