C#中复杂的可选字符串连接和格式化

时间:2016-07-14 19:05:23

标签: c# .net

如何构造一个C#函数,它接受多个字符串并以复杂的模式连接/格式化它们,具体取决于它们是否为空/空?例如,假设我有三个字符串A,B和C,并希望返回如下:

+------+------+---------+---------------------------+
| A    | B    | C       | Result                    |
+------+------+---------+---------------------------+
| ""   | ""   | ""      | ""                        |
+------+------+---------+---------------------------+
| "4"  | ""   | ""      | "4p"                      |
+------+------+---------+---------------------------+
| "8"  | "15" | ""      | "8 - 15p"                 |
+------+------+---------+---------------------------+
| ""   | ""   | "blue"  | "blue section"            |
+------+------+---------+---------------------------+
| ""   | "16" | "red"   | "16p, red section"        |
+------+------+---------+---------------------------+
| "23" | "42" | "green" | "23 - 42p, green section" |
+------+------+---------+---------------------------+

如您所见,如果存在特定元素,则会添加一些格式部分,而依赖于多个元素的其他部分则会添加。这一切只需要通过手动if语句和连接来完成,还是有一些工具可以组合这些字符串?

1 个答案:

答案 0 :(得分:2)

对于您所描述的简单内容,您可以编写相对较少的if语句。或者,您可以创建多个格式字符串并选择正确的字符串。只有8种不同的可能性,因此您可以使用枚举轻松编写代码。考虑:

[Flags]
StringFormatFlags
{
    AExists = 4,
    BExists = 2,
    CExists = 1,
    FormatNone = 0,
    FormatC = CExists, // 1
    FormatB = BExists, // 2
    FormatBC = BExists | CExists, // 3
    FormatA = AExists, // 4
    FormatAC = AExists | CExists, // 5
    FormatAB = AExists | BExists, // 6
    FormatABC = AExists | BExists | CExists, // 7
};

然后,您可以根据A,B和C的值初始化值:

StringFormatFlags val = StringFormatFlags.FormatNone;
if (!string.IsNullOrEmpty(A))
    val |= StringFormatFlags.AExists;
if (!string.IsNullOrEmpty(B))
    val |= StringFormatFlags.BExists;
if (!string.IsNullOrEmpty(C))
    val |= StringFormatFlags.CExists;

这将为您提供0到7之间的值,与该枚举中的Format值之一相对应。

现在,创建8个不同的格式字符串:

string[] FormatStrings = new string[]
{
    "{1}{2}{3}", // 0 - None
    "{1}{2}{3}", // 1 - C only
    "{1){2}p{3}", // 2 - B only
    "{1}{2}p,{3}", // 3 - B and C
    "{1}p{2}{3}", // 4 - A only
    "{1}p{2},{3}", // 5 - A and C
    "{1} - {2}p{3}",    // 6 - A and B
    "{1} - {2}p,{3}",  // A, B, C
}

最后:

string formattedString = string.Format(FormatStrings[(int)val], A, B, C);

这里的关键是大括号中的数字(即{2})如果相应的参数为空或空,则不会生成任何内容。