我正在创建一个简单的类来生成假的lorem ipsum文本,所以我有:
public static class LoremIpsumGenerator {
private static Random _random = new Random();
private static String _lorem = Constants.LoremIpsumText;
private static IEnumerable<String> _words = _lorem.ToWordList();
public static String GetText(Int32 totalLength = 200, Int32? paragraphLength = null) {
IList<String> words = _words.OrderBy(x => Guid.NewGuid()).ToList();
String text = String.Empty;
String paragraph = _lorem.Substring(0, 12);
Int32 index = 0;
while (text.Length < totalLength) {
//Int32 a = (paragraphLength == null ? _random.Next(20, 80) : paragraphLength.Value);
Int32 limit = _random.Next(20, 80);
while (paragraph.Length < limit) {
paragraph += (String.IsNullOrEmpty(paragraph) ? words[index].ToFirstLetterUppercase() : words[index].ToLower()) + " ";
index++;
if (index > words.Count)
index = 0;
}
paragraph = paragraph.TrimEnd();
text += paragraph + ". ";
paragraph = String.Empty;
}
return text;
} // GetText
} // LoremIpsumGenerator
问题在于:
Int32 l = (paragraphLength == null ? _random.Next(20, 80) : paragraphLength.Value);
它给了我几乎总是相同的价值......例如我得到了:
21, 21, 47, 47, 47, 47, 47, 47, 47, 47, 47
or
50, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50
有谁知道如何防止这种情况?
更新
public static class LoremIpsumGenerator {
private static Random _random = new Random();
private static String _lorem = Constants.LoremIpsumText;
private static IEnumerable<String> _words = _lorem.ToWordList();
public static String GetText(Int32 totalLength = 200, Int32? paragraphLength = null) {
IList<String> words = _words.OrderBy(x => Guid.NewGuid()).ToList();
String text = String.Empty;
String paragraph = _lorem.Substring(0, 12);
Int32 index = 0;
while (text.Length < totalLength) {
Int32 limit = _random.Next(20, 80);
while (paragraph.Length < limit) {
paragraph += (String.IsNullOrEmpty(paragraph) ? words[index].ToFirstLetterUppercase() : words[index].ToLower()) + " ";
index++;
if (index > words.Count)
index = 0;
}
paragraph = paragraph.TrimEnd();
text += paragraph + ". ";
paragraph = String.Empty;
}
} // GetText
} // LoremIpsumGenerator