這是.NET反射的一個有趣小例子: 通過反射將變量值轉為變量名本身.
當然要先添加命名空間:using System.Reflection;
示例代碼如下:
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 }
代碼已經相當清晰,所以就不多做解釋了~
本文原址:http://www.cnblogs.com/Interkey/p/3460566.html
.NET的反射可參考:反射概述 或 了解.NET中反射機制的使用與分析。
.NET反射雖然執行效率相對較慢,但在軟件破解過程中,作用卻非常大。這里就留給有心人了~
本文的代碼已上傳到附件~
本文參考了以下文章:
因為感覺挺有意思的,所以就分享給大家~
還有,覺得有意思就頂吧~