帮助处理C#中内容字符串数组的HashTables

nam*_*mco 8 c# arrays string hashtable


我有这样的代码.

Hashtable ht = new HashTable();
ht["LSN"] = new string[5]{"MATH","PHIS","CHEM","GEOM","BIO"};
ht["WEEK"] = new string[7]{"MON","TUE","WED","THU","FRI","SAT","SUN"};
ht["GRP"] = new string[5]{"10A","10B","10C","10D","10E"};
Run Code Online (Sandbox Code Playgroud)

现在我想从这个ht获得价值,如下所示.

string s = ht["LSN"][0];
Run Code Online (Sandbox Code Playgroud)

但它给出了错误.那么我该如何解决这个问题呢.

Nic*_*ick 9

我想你想使用泛型字典而不是Hashtable:

Dictionary<String, String[]> ht = new Dictionary<string, string[]>();

ht["LSN"] = new string[5] { "MATH", "PHIS", "CHEM", "GEOM", "BIO" };
ht["WEEK"] = new string[7] { "MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN" };
ht["GRP"] = new string[5] { "10A", "10B", "10C", "10D", "10E" };

string s = ht["LSN"][0];
Run Code Online (Sandbox Code Playgroud)

这应该编译好.

否则你需要执行一个演员,如:

string s = ( ht[ "LSN" ] as string[] )[ 0 ];
Run Code Online (Sandbox Code Playgroud)