2014-10-09 37 views
-2

請描述我如何工作方法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); 
    } 

} 
+0

http://msdn.microsoft.com/en-us/library/system.iformatprovider.getformat(v=vs.110).aspx – CodeCaster 2014-10-09 17:40:23

+0

我讀過這個例子,但不明白。 – Makeda 2014-10-09 17:56:56

回答

0

I don't undersand what object we put in "formatType"看看方法簽名。 formatTypeType。你通過它Type。它在IFormatProvider中定義,因此您可能不需要自己調用它。還有其他一些方法會預期IFormatProvider,因此它可以調用GetFormat

至於返回thisIFormatProvider有一個單一的方法GetFormat,返回任何Type被傳遞給GetFormat的對象。在這種情況下,執行GetFormat(因爲它也實現了ICustomFormatter)的對象是相同的TimeWordFormatter。所以它只是用C#關鍵字this返回當前實例。

+0

在我的例子中,我把什麼對象放在「formatType」中?我在哪裏得到它? 爲什麼我們返回當前實例?我不明白爲什麼我們應該在這個例子中使用GetFormat。 – Makeda 2014-10-09 17:59:19

+0

@Makeda:你不使用'GetFormat'。 'string.Format'將調用'GetFormat'並要求一個'ICustomFormatter'。你的'TimeWordFormatter'會自動返回,因爲它是'ICustomFormatter'。 – 2014-10-09 18:06:22