【问题标题】:Cast From Arraylist To a String从 Arraylist 转换为字符串
【发布时间】:2013-12-02 14:57:44
【问题描述】:

我正在使用 Random 类从 ArrayList 中获取一个元素。目前我正在尝试使用 ToString 将此元素转换为字符串(不成功)。我如何将 Solutions[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;

【问题讨论】:

  • 不要使用ArrayList 使用List<string> 你不需要转换它,因为它已经是一个字符串

标签: c# string arraylist casting


【解决方案1】:
string s = Solutions[r].ToString(); // you're missing brackets

【讨论】:

    【解决方案2】:

    使用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];
    

    【讨论】:

      【解决方案3】:
      List<String> solutions = new List<String>();
      
      solutions.Add("The Odyssey");
      solutions.Add("Dune");
      // and so on
      

      那么你可以:

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

      【讨论】:

        猜你喜欢
        • 2019-09-04
        • 1970-01-01
        • 2012-04-28
        • 2011-09-13
        • 2015-07-22
        • 2014-09-19
        • 2014-05-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多