从Arraylist转换为字符串

时间:2013-12-02 14:57:45

标签: c# string arraylist casting

我使用Random Class从ArrayList中获取一个元素。目前我正在尝试使用ToString将此元素转换为字符串(失败)。我如何将解决方案[r]转换为字符串?

ArrayList Solutions = new ArrayList(5);
Solutions.Add("The Odyssey");
Solutions.Add("Dune");
Solutions.Add("Sherlock Holmes");
Solutions.Add("Othello");
Solutions.Add("Of Mice and Men");

Random ran = new Random();
int r = ran.Next(Solutions.Count); 

string s = Solutions[r].ToString;

3 个答案:

答案 0 :(得分:2)

string s = Solutions[r].ToString(); // you're missing brackets

答案 1 :(得分:0)

使用IList<string>可以更轻松,更干净。

IList<string> Solutions = new List<string>(5);
Solutions.Add("The Odyssey");
Solutions.Add("Dune");
Solutions.Add("Sherlock Holmes");
Solutions.Add("Othello");
Solutions.Add("Of Mice and Men");

Random ran = new Random();
int r = ran.Next(Solutions.Count); 

string s = Solutions[r];

答案 2 :(得分:0)

List<String> solutions = new List<String>();

solutions.Add("The Odyssey");
solutions.Add("Dune");
// and so on

然后你可以:

label1 = solution[random_index]; // starts with 0