Ang*_*ker 5 refactoring c#-3.0
我有以下函数,它将一个字符串作为参数并重复多次(也是一个参数).我觉得这已经存在于框架中,或者至少可以做得更好.有什么建议?
private string chr(string s, int repeat)
{
string result = string.Empty;
for (int i = 0; i < repeat; i++)
{
result += s;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
函数式编程风格的方法:(
至少需要 C# 3.0)
static class StringRepetitionExtension
{
public static string Times(this int count, string what)
{
return count > 0 ? string.Concat(what, (count-1).Times(what))
: string.Empty;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
3.Times("Foobar") // returns "FoobarFoobarFoobar"
Run Code Online (Sandbox Code Playgroud)
(当然不是最有效的解决方案,并且由于递归,总是存在堆栈溢出的危险,并且 的值不合理地大count;但我仍然想分享一种稍微不同的、易于理解的方法。)