所以如果将变量的字符串名称传递给方法,我知道要使用哪个变量。
在下面的示例中,我需要帮助的区域是PrintVar(字符串)...将字符串参数转换为变量...以便打印出“here be variable 1”和“here be variable 2”分别...谢谢!
class ReflectionTest
{
class MyObj
{
private string myvar;
public MyObj(string input)
{ this.myvar = input; }
public override string ToString()
{ return ("here be " + myvar); }
}
class MyClass
{
private MyObj var1;
private MyObj var2;
public MyClass()
{
var1 = new MyObj("variable 1");
var2 = new MyObj("variable 2");
}
public void PrintVar(string theVariable)
{
Console.WriteLine(theVariable);
}
}
static void Main()
{
MyClass test = new MyClass();
test.PrintVar("var1");
test.PrintVar("var2");
}
}
答案 0 :(得分:6)
如果您需要按名称获取内容,那么个人我首先要在内部实现中使用字典,即
private readonly Dictionary<string,MyObj> fields =new Dictionary<string,MyObj>();
public MyClass()
{
fields["var1"] = new MyObj("variable 1");
fields["var2"] = new MyObj("variable 2");
}
public void PrintVar(string fieldName)
{
Console.WriteLine(fields[fieldName]);
}
另一种选择是反思(GetType().GetFields()
):
public void PrintVar(string fieldName)
{
Console.WriteLine(GetType().GetField(fieldName,
BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this));
}