我会将它完全抽象为一个单独的静态类或资源:
public static class MyStringResources
{
public static readonly string StringLiteral =
@"This {0} a really long string literal
I don't want {1} to have {2} at
the beginning of each line, so I have
to break the indentation of my program";
}
使用如下:
stringLiteral = String.Format(MyStringResources.StringLiteral, var1, var2, var3);
更好的是,这样你可以有一个很好的函数,它需要预期变量的数量:
public static class MyStringLiteralBuilder
{
private static readonly string StringLiteral =
@"This {0} a really long string literal
I don't want {1} to have {2} at
the beginning of each line, so I have
to break the indentation of my program";
public static string Build(object var1, object var2, object var3)
{
return String.Format(MyStringResources.StringLiteral, var1, var2, var3);
}
}
然后你就不会意外遗漏变量(甚至可能将它们强输入为数字、布尔值等)
stringLiteral = MyStringLiteralBuilder.Build(var1, var2, var3);
stringLiteral = MyStringLiteralBuilder.Build(var1, var2); //compiler error!
当然,在这一点上,您可以使用这些构建器做几乎任何您想做的事情。为程序中每个特殊的大“stringLiteral”创建一个新的构建器。也许static
它们可以是您可以获取/设置关键属性的实例,而不是让它们成为实例,然后您也可以给它们起好听的名称:
public class InfoCardSummary
{
public string Name { get; set; }
public double Age { get; set; }
public string Occupation { get; set; }
private static readonly string FormattingString =
@"This person named {0} is a pretty
sweet programmer. Even though they're only
{1}, Acme company is thinking of hiring
them as a {2}.";
public string Output()
{
return String.Format(FormattingString, Name, Age, Occupation);
}
}
var info = new InfoCardSummary { Name = "Kevin DiTraglia", Age = 900, Occupation = "Professional Kite Flier" };
output = info.Output();