C# 反射修改私有靜態成員變數 反射獲取修改類中的屬性值
阿新 • • 發佈:2019-02-07
//動態連結庫中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); } /// <summary> /// 獲取key /// </summary> /// <returns></returns> 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;};
}
/// <summary> /// 獲取修改類中的屬性 /// </summary> /// <returns></returns> publicvoid GetAndSetProperty() {
Test t = new Test();
PropertyInfo p=t.GetType().GetProperty("StrTest");
p.SetValue(p,"test"); }
/// <summary> /// 獲取key /// </summary> /// <returns></returns> 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(); }