gpt4 book ai didi

c# - 使用使用空格的字符串文字保持代码结构

转载 作者:IT王子 更新时间:2023-10-29 04:27:51 26 4
gpt4 key购买 nike

这是一个有点奇怪的问题,我在想出搜索词时遇到了麻烦。如果我的程序中有一个多行字符串文字,是否可以在不向我的字符串文字中添加不需要的空格的情况下保持代码的缩进一致?

例如:

if (true)
{
if (!false)
{
//Some indented code;
stringLiteral = string.format(
@"This is a really long string literal
I don't want it to have whitespace at
the beginning of each line, so I have
to break the indentation of my program
I also have vars here
{0}
{1}
{2}",
var1, var2, var3);
}
}

这可能只是我的强制症在说话,但无论如何要保持我的程序的缩进而不向字符串添加不需要的空格,或者必须逐行构建它(真正的字符串是一个超长的 string.format 那是20~ 行,里面有 12 个变量)?

最佳答案

我会将它完全抽象为一个单独的静态类或资源:

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);
}
}

这样你就不会意外遗漏变量(甚至可能将它们强类型化为数字、 bool 值等)

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();

关于c# - 使用使用空格的字符串文字保持代码结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17307786/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com