[英]How does this .NET code work?
this code is part of NBuilder . 此代码是NBuilder的一部分。 I'm having a bad day .. and to prove it, I don't understand what this (simple) code is trying to do.
我今天过得很糟糕..为了证明这一点,我不明白这个(简单的)代码想要做什么。
Here are the answers, with the code after it. 这里是答案,其后是代码。
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
and the code... 和代码...
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();
}
I would have thought that the method should return x number of phrases or a random phrase of at least the length specified? 我以为该方法应返回x个短语或至少指定长度的随机短语?
The code returns a random phrase less than or equal to the length specified, in characters. 该代码以字符为单位返回小于或等于指定长度的随机短语。 The key is this line:
关键是这一行:
if (result.Length + word.Length + 1 > length)
This guarantees that the length in characters of the result (including the newly-added word) doesn't exceed the value of length
. 这样可以确保结果的字符长度(包括新添加的单词)不超过
length
的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.