請描述我如何工作方法GetFormat。下面我給出了一個典型的方法示例。當我們調用string.Format和爲什麼返回「this」時,我不會在其中聲明我們放入「formatType」的對象?工作方法如何GetFormat
感謝您的回答。
class TimeWordFormatter : IFormatProvider, ICustomFormatter
{
static readonly string[] hours = { "h", "hours", "H" };
static readonly string[] minutes = { "m", "minutes", "M" };
static readonly string[] seconds = { "s", "seconds", "S" };
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter))
{
return this;
}
else
{
return null;
}
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (arg == null || !(arg is TimeSpan) || format != "W")
return string.Format("{0:" + format + "}", arg);
TimeSpan time = (TimeSpan)arg;
string hh = GetCase(time.Hours, hours);
string mm = GetCase(time.Minutes, minutes);
string ss = GetCase(time.Seconds, seconds);
return string.Format("{0:%h} {1} {0:%m} {2} {0:%s} {3}", time, hh, mm, ss);
}
static string GetCase(int value, string[] options)
{
value = Math.Abs(value) % 100;
if (value > 10 && value < 15)
return options[2];
value %= 10;
if (value == 1) return options[0];
if (value > 1 && value < 5) return options[1];
return options[2];
}
static void Main()
{
var now = DateTime.Now;
string formattedTime = string.Format(new TimeWordFormatter(), "{0:W}", now.TimeOfDay);
Console.WriteLine(formattedTime);
}
}
http://msdn.microsoft.com/en-us/library/system.iformatprovider.getformat(v=vs.110).aspx – CodeCaster 2014-10-09 17:40:23
我讀過這個例子,但不明白。 – Makeda 2014-10-09 17:56:56