簡體   English   中英

從Arraylist轉換為字符串

[英]Cast From Arraylist To a String

我使用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;
string s = Solutions[r].ToString(); // you're missing brackets

使用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];
List<String> solutions = new List<String>();

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

那么你也能:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM