简体   繁体   中英

How do I use a variable to identify another variable in C#?

Is there a way to basically do this:

string x = "hi";
int hi = 3;
Console.WriteLine([x].ToString());

get what I'm trying to do? I want to print "3", not "hi." I want to use x to reference to hi. how might I do this?

What about a Dictionary.

Dictionary<string, int> data = new Dictionary<string, int>();
data["hi"] = 3;

Console.WriteLine(data["hi"]); // prints 3

You could try (sorry i'm typing from my phone)

class MyClass
{

  public int x {get;set;}
  MyClass()
  {
      x = 3;
  }

  void Foo()
  {
      Type type = GetType();
      PropertyInfo pInfo = type.GetProperty("x");

      object xValue= pInfo.GetValue(this, null);
      Console.Writeln(xValue); 
  }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM