创建随机数组字符串类型

时间:2014-06-03 21:10:16

标签: c# arrays random

我正在制作一个程序,可以生成人,精灵和其他种族等的描述。

它涉及很多数组和列表,其中有一个单词被挑选然后放入一个句子中。示例数组看起来像:

public string[] hairfront = {
        "side swept bangs", "straight bangs", "choppy bangs", "wispy bangs",
        "parted straight bangs", "parted choppy bangs", "blunt single length bangs",
        "bangs shorter on one side than the other", "pixi cut bangs"}

然后,随机类将选择一个数字并返回相应的字符串,只要我有RAE(array name)

示例:"The person has " + RAE(hairfront)

我想将RAE作为一种数组类型,它将有一个方法可以选择一个随机字符串放入句子。

以下伪代码描述了我希望代码看起来的样子:

new RAE(hair)={ "blah", "brown", "long"}
Public string generate_description "the persons hair is" RAE(hair)
it will become "the persons hair is brown"

1 个答案:

答案 0 :(得分:1)

正如你所说,你可以将它包装在一个类中:

public class RandomStringGenerator
{
   private string[] data;  //Data holder
   private Random rng = new Random(); //Class level so it seeds once

   public RandomStringGenerator(string[] startData)
   {
       data = startData;
   }

   public string GetRandomElement()
   {
       return data[rng.Next(0, data.Length)];
   }
}

您将初始化数组传递给它,然后在每次需要新内容时调用GetNextElement:

RandomArray hairRandomizer = new RandomArray (new string[] { "side swept bangs", "straight bangs", "choppy bangs", "wispy bangs", "parted straight bangs", "parted choppy bangs", "blunt single length bangs", "bangs shorter on one side than the other", "pixi cut bangs"});
string myHair = hairRandomizer.GetNextElement();

正如AlexeiLevenkov指出的那样,同时创造大量这些是一个糟糕的选择。如果您这样做,则需要在更高级别创建Random对象并将其传递到:

public class RandomStringGenerator
{
   private string[] data;  //Data holder
   private Random rng; //Not instantiated since we pass it in

   public RandomStringGenerator(string[] startData, Random rngToUse)
   {
       data = startData;
       rng = rngToUse;
   }
   ... //Same as before
}