简体   繁体   中英

Cast From Arraylist To a String

I'm getting one element from the ArrayList using the Random Class. Currently I'm trying to cast this element into a string (unsuccessfully) using ToString. How would i Cast Solutions[r] into a string?

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

using IList<string> makes it much more easy and clean.

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

Then you can:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM