在String.Format中包含If Else语句

Nar*_*ana 8 c# string string-formatting

我有以下状态.

  timespan = timespan.FromSeconds(236541)
  formattedTimeSpan = String.Format("{0} hr {1} mm {2} sec", Math.Truncate(timespan.TotalHours), timespan.Minutes, timespan.Seconds)
Run Code Online (Sandbox Code Playgroud)

如果超过一小时,我必须将其格式化为"hrs mn sec".我想在上面的String.Format中检查这个.

谢谢.

pol*_*nts 9

可能最干净的方法就是自己编写ICustomFormatter.这是一个方便的多元化格式的示例:

using System;

public class PluralFormatter : IFormatProvider, ICustomFormatter {

   public object GetFormat(Type formatType) {
      if (formatType == typeof(ICustomFormatter))
         return this;
      else
         return null;
   }

   public string Format(string format, object arg, 
                          IFormatProvider formatProvider)
   {   
      if (! formatProvider.Equals(this)) return null;

      if (! format.StartsWith("^")) return null;

      String[] parts = format.Split(new char[] {'^'});
      int choice = ((int) arg) == 1 ? 1 : 2;
      return String.Format("{0} {1}", arg, parts[choice]);
   }

   public static void Main() {
      Console.WriteLine(String.Format(
         new PluralFormatter(),
         "{0:^puppy^puppies}, {1:^child^children}, and {2:^kitten^kittens}", 
         13, 1, 42
      ));
   }
}
Run Code Online (Sandbox Code Playgroud)

正如人们可能已经猜到的那样(并且在ideone.com上看到):

13 puppies, 1 child, and 42 kittens
Run Code Online (Sandbox Code Playgroud)

MSDN链接


Bra*_*ger 7

一种可能性是制作格式字符串的复数部分,并写:

formattedTimeSpan = String.Format("{0} hr{1} {2} mm {3} sec",
    Math.Truncate(timespan.TotalHours),
    Math.Truncate(timespan.TotalHours) == 1 ? "" : "s",
    timespan.Minutes,
    timespan.Seconds);
Run Code Online (Sandbox Code Playgroud)

如果输出显示除"1小时"之外的任何内容,这将在输出中插入"s".

请注意,这对本地化不友好:其他语言与复数形式不同于英语.