StringBuilder的格式结构

时间:2016-08-11 20:04:56

标签: c# formatting stringbuilder

private void add_value_to_row(client_file client_file, ref StringBuilder OutputCustomer, String value)
{
   if (client_file.output_format == "txt") 
      if (value = "the first value in add_value_to_row")
         OutputCustomer.AppendFormat("{0}", value); 
      else if (value = "every other value in add_value_to_row")  
         OutputCustomer.AppendFormat("\t{0}", value);
}

我有一个上面写的函数,它接受来自" x"的输入。并根据以下代码创建.txt格式的数据行。我想知道如何编写嵌套的if语句,以便它执行用引号写的内容?根据以下数据的最终输出应输出OutputCustomer.AppendFormat("{0}\t{1}\t{2}\t{3}\t{4}", x.url, x.company, x.Country, x.vendor, x.product);

OutputCustomer = new StringBuilder();

add_value_to_row(clientInfo.cf, ref OutputCustomer, x.url);
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.company);
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.Country);
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.vendor);
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.product);

2 个答案:

答案 0 :(得分:0)

为什么要逐个添加项目?将对象提供给方法并让它决定。

private void add_value_to_row(client_file client_file, ref StringBuilder OutputCustomer, YourType value)
{
   if (client_file.output_format == "txt") 

     OutputCustomer.AppendFormat("{0}\t{1}\t{2}\t{3}\t{4}",
     value.url,value.company,value.Country,value.vendor,value.product); 

}

并像这样称呼它

add_value_to_row(clientInfo.cf, ref OutputCustomer, x);

否则你必须在方法签名

中给出一个bool或int

<强>更新

如果你真的想按照你的方式使用你的方法,你需要在签名中使用布尔值

private void add_value_to_row(client_file client_file, ref StringBuilder OutputCustomer, String value, bool isFirst=false)
{
   if (client_file.output_format == "txt") 
      if (isFirst)
         OutputCustomer.AppendFormat("{0}", value); 
      else  
         OutputCustomer.AppendFormat("\t{0}", value);
}

并像这样称呼它

add_value_to_row(clientInfo.cf, ref OutputCustomer, x.url, true);
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.company);
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.Country);
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.vendor);
add_value_to_row(clientInfo.cf, ref OutputCustomer, x.product);

另外请注意,您可以将它作为可选参数,这样您就不需要每次都写它

答案 1 :(得分:0)

看起来您正在尝试创建制表符分隔的输出行。更简单的方法是:

string outputCustomer = string.Join("\t", new {x.url, x.company, x.Country, x.vendor, x.product});

请参阅String.Join