2011-03-12 143 views
0

有沒有辦法從根本上做到這一點:如何使用變量在C#中標識另一個變量?

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

得到我想要做什麼?我想打印「3」,而不是「嗨」。我想用x來引用hi。我該怎麼做?

+5

你爲什麼要這麼做?這聽起來像你應該使用「字典」。 – 2011-03-12 03:44:25

+0

您可以使用反射。當然,不適用於局部變量(糾正我,如果我錯了?)。 – Rob 2011-03-12 03:47:07

+2

考慮離開PHP並學習真正的編程技術,閱讀Matts評論和rcravens答案。 – stefan 2011-03-12 03:55:17

回答

0

你可以嘗試(對不起,我從我的手機上輸入)

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); 
    } 


} 
5

字典怎麼樣?

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

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

應該在你的例子中顛倒int和string來完成他想要的東西?或者我只是密集? – Pete 2011-03-12 03:49:51

+0

好的。我會更新。謝謝。 – rcravens 2011-03-12 03:53:14

+0

現在看起來不錯;)+1 – Pete 2011-03-12 03:55:27

相關問題