经过反射将变量值转为变量名自己

这是.NET反射的一个有趣小例子:  经过反射将变量值转为变量名自己. html

固然要先添加命名空间:using System.Reflection;this

示例代码以下:spa

    class Program
    {
        string name = "strA";
        string strA = "strB";
        string strB = "Hello World~";

        static void Main(string[] args)
        {
            Program p = new Program();
            p.GetTypeValue();

            p.GetStrValue(p.name);

            p.SetStrValue(p.strA);

            Console.ReadKey();
        }
        //本文原址:http://www.cnblogs.com/Interkey/p/3460566.html

        /// <summary>
        /// 获取全部FieldInfo的值
        /// </summary>
        void GetTypeValue()
        {
            Console.WriteLine("Method: GetTypeValue");
            FieldInfo[] fis = this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
            foreach (FieldInfo fi in fis)
            {
                Console.WriteLine(fi.Name + " 的值为:" + fi.GetValue(this).ToString());
            }
            Console.WriteLine();
        }

        /// <summary>
        /// 获取字符串str对应的变量名的变量值对应的变量值
        /// </summary>
        /// <param name="str"></param>
        void GetStrValue(string str)
        {
            Console.WriteLine("Method: GetStrValue");
            Type type = this.GetType();

            //获取字符串str对应的变量名的变量值
            Console.WriteLine(type.GetField(str, BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this).ToString());

            Console.WriteLine(
                type.GetField(
                    type.GetField(str, BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this).ToString(),
                        BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this).ToString()
            );
            Console.WriteLine();
        }

        /// <summary>
        /// 设置字符串str对应的变量名的变量值
        /// </summary>
        /// <param name="str"></param>
        void SetStrValue(string str)
        {
            Console.WriteLine("Method: SetStrValue");

            //赋值前输出
            Console.WriteLine(this.GetType().GetField(str, BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this));

            //进行赋值操做
            this.GetType().GetField(str, BindingFlags.NonPublic | BindingFlags.Instance).SetValue(this, "Hello Interkey~");

            //赋值后输出
            Console.WriteLine(this.GetType().GetField(str, BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this));
            Console.WriteLine();
        }
        //本文原址:http://www.cnblogs.com/Interkey/p/3460566.html
    }

代码已经至关清晰,因此就很少作解释了~code

本文原址:http://www.cnblogs.com/Interkey/p/3460566.htmlhtm

.NET的反射可参考:反射概述 或 了解.NET中反射机制的使用与分析blog

.NET反射虽然执行效率相对较慢,但在软件破解过程当中,做用却很是大。这里就留给有心人了~ip

本文的代码已上传到附件~ci

 

本文参考了如下文章:字符串

C#里面中将字符串转为变量名get

经过字符串 反射 成类的实例

字符串转为变量名,经过字符串给变量赋值

由于感受挺有意思的,因此就分享给你们~

还有,以为有意思就顶吧~

相关文章
相关标签/搜索