通过反射将变量值转为变量名本身
当然要先添加命名空间: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();
}
//
/// <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();
}
//
}