C# 中放射获取当前变量的值

来源:互联网 发布:衣服布料淘宝 编辑:程序博客网 时间:2024/05/19 20:39

首先是获取一个对象中成员变量的值

public class Program    {        public string str = "spp";        public string spp = "Hello World!";        public static void Main(string[] args)        {            Program p = new Program();            Console.WriteLine(p.GetType().GetField(p.str).GetValue(p).ToString());            Console.ReadKey();        }    }


获取并修改静态变量的值

//动态链接库中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>        public void 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();        }


 



 

0 0
原创粉丝点击