2014-10-27 106 views
1

是否有可能在asp.net c#中使用另一个变量引用变量/数组? EG。在变量中使用asp.net c存储变量名称#

alfaromeo = new string[] {"lots of stuff"}; 
astonmartin = new string[] {"lots of stuff"}; 
audi = new string[] {"lots of stuff"}; 
bentley = new string[] {"lots of stuff"}; 
bmw = new string[] {"lots of stuff"}; 

etc 

string targetArray = "audi"; 

for(int i=0; i<targetArray.Length; i++){ 
    // do stuff with tha array 
} 

有一个原因,数组都被称为不同的名称,我没有使用多维数组来引用它们。

可以这样做,还是我需要使用某种查找数组引用它们?

在此先感谢。

+0

'串targetArray =“audi”;'这是一个'字符串'还是'字符串[]'? – Marco 2014-10-27 10:01:59

+0

一个字符串。这将是一个刚刚存储我想要使用的数组名称的地方,除非您看到比我更合乎逻辑的事情。这是非常可能的:) – 2014-10-27 10:04:27

回答

2

不,不是局部变量。

我宁愿把东西在一本字典:

var dict = new Dictionary<string, string[]> 
{ 
    { "alfaromeo", new string[] {"lots of stuff"} } 
    // etc... 
} 

或者,如果你坚持的变量,把它们放入一个类的字段,并使用反射:

class Z { 
    public static string[] alfaromeo = new string[] {"lots of stuff"}; 
} 
// ... 
typeof(Z).GetField("alfaromeo", BindingFlags.Static | BindingFlags.Public).GetValue(null); 
+0

对不起,如果我使用字典,如何使用字典一旦存储,我可以参考它们吗? – 2014-10-27 10:05:58

+0

'dict [“alfaeomeo”]'字符串成为字典中的关键字。试试[这里](http://www.dotnetperls.com/dictionary)寻求更好的帮助 – 2014-10-27 10:22:13