2016-07-14 38 views
-2

你会如何构造一个C#函数,它在几个字符串并连接/格式它们取决于他们是否是空/空的复杂模式?举例来说,假设我有三个串A,B和C,并希望返回如下:复杂的可选字符串连接和格式在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" | 
+------+------+---------+---------------------------+ 

正如你所看到的,有如果一个特定的元素存在添加一些格式片,其他依赖于多个元素。这是否只需要手动完成,如果语句和连接,或者是否有一些工具可以组装这样的字符串?

+2

在输出字符串为“额外”有明确的规则?如果没有,我不认为有一种通用的方式来做到这一点。如果有......我仍然怀疑有。虽然我会解决它作为一个静态辅助方法或扩展方法。 –

+0

此外,我会*不*建议与if语句做。采用面向对象的方法。构建一堆类和自定义的字符串构建器。 –

+0

上述序列还有其他组合吗?例如,如果A = 4,B =“”,C =“蓝色”呢? – Steve

回答

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,0的一个相应的该枚举中的值为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})的数量不会产生任何东西,如果相应的参数为空或空。

+0

稍微优化一下,但我认为,就像我将要获得的一样好。 – tloflin