C#使用const字符串互相参与

时间:2018-05-07 19:10:55

标签: c# string formatting refactoring constants

对于这个特定的需要,我有两个包含参数的const字符串,如下所示:

private const string myString = "The operation #{0} has been completed successfully in {1} seconds";

这种类型的常量当然会在稍后与String.Format()一起使用,以生成反馈消息。

现在我面临一个特定的案例,我有两个常量。我的例子不是真实案例,出于隐私目的,所以它看起来不是很有用甚至是逻辑上的,但我向你保证,真实的东西在上下文中是有意义的。对于有同样问题的假案,我无法理解:

private const string shortFormat = "operation {0} out of {1}";
private const string longFormat = "During step one, an error was encountered on operation {0} out of {1}, and during step two, an error was encountered on operation {2} out of {3}";

您可以在此处看到明显的冗余。其中一个常数被使用了两次在第二个常量内,实际上是相同的目的,只是在更大的图片中。

如果只使用一次,我可以像这样重复使用它:

private const string shortFormat = "operation {0} out of {1}";
private const string longFormat = "During step one, an error was encountered on " + shortFormat + " so the process has not completed step two.";

这看起来会好得多。但我不知道如何在第一个例子中使用它两次。如果我只是简单地插入shrotFormat两次,那么我将复制参数0和1,因此运行时的字符串将如下所示:

"During step one, an error was encountered on operation {0} out of {1}, and during step two, an error was encountered on operation {0} out of {1}"

这显然不适用于string.Format()

中的4个不同参数

如何保持不重复,同时保持所有四个参数号不同,并且可以使用4个值?

1 个答案:

答案 0 :(得分:1)

可以多次使用string.Format

private const string stepFormat= "operation {0} out of {1}";
private const string twoStepMessage = "During step one, an error was encountered on {0}, and during step two, an error was encountered on {1}";

public string CreateMessage(int s1, int s1total, int s2, int s2total)
{
    string stepOne = string.Format(stepFormat, s1, s1total);
    string stepTwo = string.Format(stepFormat, s2, s2total);
    return string.Format(twoStepMessage, stepOne, stepTwo);
}

当然,这要求调用代码知道消息的结构,因为它不能简单地将值提供给单个格式。