Type.GetField()通过变量名来得到变量
程序代码:class Program
{
static void Main(string[] args)
{
Temp t = new Temp()
{
Age = 11, Id = "2", Name = "AA"
};
string name = t.GetValueByType("name"); //这里对应TEMP类的string name
string id = t.GetValueByType("id");
Console.WriteLine("{0},{1}", name, id);
}
}
class Temp
{
public string GetValueByType(string type)
{
FieldInfo fi = this.GetType().GetField(type, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.NonPublic);
if (fi == null)
return "";
else
return (string)fi.GetValue(this);
}
string name = "", id = "";
int age = 0;
public int Age
{
get { return age; }
set { age = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Id
{
get { return id; }
set { id = value; }
}
}


