我不认为您可以使用运算符重载扩展 System.String,但您可以创建一个字符串包装类来做到这一点。
public class StringWrapper
{
public string Value { get; set; }
public StringWrapper()
{
this.Value = string.Empty;
}
public StringWrapper(string value)
{
this.Value = value;
}
public static StringWrapper operator *(StringWrapper wrapper,
int timesToRepeat)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < timesToRepeat; i++)
{
builder.Append(wrapper.Value);
}
return new StringWrapper(builder.ToString());
}
}
然后称它为...
var helloTimesThree = new StringWrapper("hello") * 3;
并从...中获取价值
helloTimesThree.Value;
当然,明智的做法是让你的函数跟踪并传入当前深度,并以此为基础在 for 循环中转储选项卡。