C# 以String.Format包含If-Else语句

C# 以String.Format包含If-Else语句,c#,string,string-formatting,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) 如果时间超过一小时,我必须将其格式化为“hrs mn sec”。我想在上面的String.Format中检查这个 谢谢。一种可能是将格

我有以下声明

  timespan = timespan.FromSeconds(236541)
  formattedTimeSpan = String.Format("{0} hr {1} mm {2} sec", Math.Truncate(timespan.TotalHours), timespan.Minutes, timespan.Seconds)
如果时间超过一小时,我必须将其格式化为“hrs mn sec”。我想在上面的String.Format中检查这个


谢谢。

一种可能是将格式字符串的复数部分改为:

formattedTimeSpan = String.Format("{0} hr{1} {2} mm {3} sec",
    Math.Truncate(timespan.TotalHours),
    Math.Truncate(timespan.TotalHours) == 1 ? "" : "s",
    timespan.Minutes,
    timespan.Seconds);
如果输出显示的不是“1小时”,则会在输出中插入“s”


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

这里没有魔力。当你可以用C语言编码时,你为什么要用
格式
可能提供的任何条件编码

为了避免重复代码,您可以将某些表达式升级为变量,并对其使用条件:

timespan = timespan.FromSeconds(236541);
int hours = Math.Truncate(timespan.TotalHours);
string hoursUnit = hours == 1 ? "hr" : "hrs";
formattedTimeSpan = String.Format("{0}{1} {2} mm {3} sec",
                        hours, hoursUnit, timespan.Minutes, timespan.Seconds);
没有“简单”的方法可以做到这一点

你可以这样做

string templateSingleHour = "{0} hr {1} mm {2} sec";
string templateMultiHour = "{0} hrs {1} mm {2} sec";
string template = Math.Truncate(timespan.TotalHours) > 1 ? templateMultiHour :templateSingleHour;
formattedTimeSpan = String.Format(template ...)
formattedTimeSpan = String.Format("{0} {3} {1} mm {2} sec", Math.Truncate(timespan.TotalHours), timespan.Minutes, timespan.Seconds, Math.Truncate(timespan.TotalHours) > 1 ? "hrs" : "hr");
还是像这样

string templateSingleHour = "{0} hr {1} mm {2} sec";
string templateMultiHour = "{0} hrs {1} mm {2} sec";
string template = Math.Truncate(timespan.TotalHours) > 1 ? templateMultiHour :templateSingleHour;
formattedTimeSpan = String.Format(template ...)
formattedTimeSpan = String.Format("{0} {3} {1} mm {2} sec", Math.Truncate(timespan.TotalHours), timespan.Minutes, timespan.Seconds, Math.Truncate(timespan.TotalHours) > 1 ? "hrs" : "hr");

您应该使用各种时间格式说明符。它极大地简化了对
Format()
的调用

var timespan = TimeSpan.FromSeconds(236541);
var formattedTimeSpan = String.Format("{0:hh} hr{1} {0:mm} mm {0:ss} sec",
    timespan, timespan.Hours != 1 ? "s" : "");

我使用了一些扩展方法来帮助我解决这类问题:

public static string Inflect(this string noun, int count)
{
 return (count == 1 || noun.EndsWith("s", StringComparison.InvariantCultureIgnoreCase)) ? noun : noun + "s";
}

public static string Of(this int count, string noun)
{
 return string.Format("{0} {1}", count, noun.Inflect(count));
}
e、 g:

“小时”。拐点(1)
:小时

“小时”。拐点(2)
:小时

0.Of(“小时”)
:“0小时”

1.Of(“小时”)
:“1小时”


5.Of(“hour”)
:“5小时”

FWIW,如果你的应用程序将被我的非英语使用者使用,那么这不是一件小事。在

上有一篇博客文章阐述了这个问题,也许最干净的方法就是自己写。下面是一个方便的复数格式示例:

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
      ));
   }
}
正如人们可能猜到的那样,输出是():

MSDN链接

谢谢您的回复。我知道这个方法。我的问题是“我能在String.Format中完成吗?”。我想你也需要在String.Format中包含“hours”。@吴哥窟-修复,谢谢!当我添加新行
:P
当您可以使用
timespan.TotalHours>=2时,为什么要编写
Math.Truncate(timespan.TotalHours)>1
时,我一定错过了这一行。我实际上使用了类似的方法。事实上,我为此写了一个完整的控件。在希伯来语中,12个或更多的词有不同的名词是很常见的(想想“一次、两次、三次”)。即使对英语来说,用两个词也会更有用:
(2)Of(“Memory”,“Memories”)
-你不想在代码中重写英语语法…+1@Kobi:是的,那真的很有用。我通常使用这种方法来解决OP所面临的问题,当我知道所讨论的名词时,它的词形是“正常的”。只要懒一点,写
“{0}hr…”
。我就以此作为答案。对于更干净的代码,我认为我们应该采纳Kobi的答案中的建议。