[英]How does this .NET code work?
此代碼是NBuilder的一部分。 我今天過得很糟糕..為了證明這一點,我不明白這個(簡單的)代碼想要做什么。
這里是答案,其后是代碼。
GetRandom.Phrase(5) == null or et or ut or do or elit or amet..
(nothing over 4 characters)
GetRandom.Phrase(4) == null or sit or sed or do ..
(nothing over 3 characters)
GetRandom.Phrase(3) == null or et or ut or do (nothing over 2 characters)
GetRandom.Phrase(2) == null
GetRandom.Phrase(1) == null
和代碼...
private static readonly string[] latinWords = { "lorem", "ipsum", "dolor",
"sit", "amet", "consectetur", "adipisicing", "elit", "sed", "do",
"eiusmod", "tempor", "incididunt", "ut", "labore", "et", "dolore",
"magna", "aliqua" };
public virtual string Phrase(int length)
{
var count = latinWords.Length;
var result = string.Empty;
var done = false;
while (!done)
{
var word = latinWords[Next(0, count - 1)];
if (result.Length + word.Length + 1 > length)
{
done = true;
}
else
{
result += word + " ";
}
}
return result.Trim();
}
我以為該方法應返回x個短語或至少指定長度的隨機短語?
該代碼以字符為單位返回小於或等於指定長度的隨機短語。 關鍵是這一行:
if (result.Length + word.Length + 1 > length)
這樣可以確保結果的字符長度(包括新添加的單詞)不超過length
的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.