通过反射将变量值转为变量名本身
通过反射将变量值转为变量名本身
这是.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反射虽然执行效率相对较慢,但在软件破解过程中,作用却非常大。这里就留给有心人了~
本文的代码已上传到附件~
本文参考了以下文章:
因为感觉挺有意思的,所以就分享给大家~
还有,觉得有意思就顶吧~


浙公网安备 33010602011771号