Mar*_*ell 14

这取决于你需要什么... new string('a',3)例如.

用于处理字符串; 你可以循环...不是很有趣,但它会工作.

使用3.5,你可以使用Enumerable.Repeat("a",3),但这会给你一系列字符串,而不是复合字符串.

如果您打算使用它,可以使用定制的C#3.0扩展方法:

    static void Main()
    {
        string foo = "foo";
        string bar = foo.Repeat(3);
    }
    // stuff this bit away in some class library somewhere...
    static string Repeat(this string value, int count)
    {
        if (count < 0) throw new ArgumentOutOfRangeException("count");
        if (string.IsNullOrEmpty(value)) return value; // GIGO            
        if (count == 0) return "";
        StringBuilder sb = new StringBuilder(value.Length * count);
        for (int i = 0; i < count; i++)
        {
            sb.Append(value);
        }
        return sb.ToString();
    }
Run Code Online (Sandbox Code Playgroud)


Gee*_*key 5

如果您只需要重复单个字符(如您的示例中所示),那么这将起作用:

Console.WriteLine(new string('a', 3))
Run Code Online (Sandbox Code Playgroud)


Bin*_*ony 5

好吧,在所有版本的.NET中重复一个字符串,你总是可以这样做

public static string Repeat(string value, int count)
{
  return new StringBuilder().Insert(0, value, count).ToString();
}
Run Code Online (Sandbox Code Playgroud)