|
| 1 | +// <Snippet2> |
| 2 | +using System; |
| 3 | + |
| 4 | +public class TestFormatter |
| 5 | +{ |
| 6 | + public static void Main() |
| 7 | + { |
| 8 | + int acctNumber = 79203159; |
| 9 | + Console.WriteLine(String.Format(new CustomerFormatter(), "{0}", acctNumber)); |
| 10 | + Console.WriteLine(String.Format(new CustomerFormatter(), "{0:G}", acctNumber)); |
| 11 | + Console.WriteLine(String.Format(new CustomerFormatter(), "{0:S}", acctNumber)); |
| 12 | + Console.WriteLine(String.Format(new CustomerFormatter(), "{0:P}", acctNumber)); |
| 13 | + try { |
| 14 | + Console.WriteLine(String.Format(new CustomerFormatter(), "{0:X}", acctNumber)); |
| 15 | + } |
| 16 | + catch (FormatException e) { |
| 17 | + Console.WriteLine(e.Message); |
| 18 | + } |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +public class CustomerFormatter : IFormatProvider, ICustomFormatter |
| 23 | +{ |
| 24 | + public object GetFormat(Type formatType) |
| 25 | + { |
| 26 | + if (formatType == typeof(ICustomFormatter)) |
| 27 | + return this; |
| 28 | + else |
| 29 | + return null; |
| 30 | + } |
| 31 | + |
| 32 | + public string Format(string format, |
| 33 | + object arg, |
| 34 | + IFormatProvider formatProvider) |
| 35 | + { |
| 36 | + if (! this.Equals(formatProvider)) |
| 37 | + { |
| 38 | + return null; |
| 39 | + } |
| 40 | + else |
| 41 | + { |
| 42 | + if (String.IsNullOrEmpty(format)) |
| 43 | + format = "G"; |
| 44 | + |
| 45 | + string customerString = arg.ToString(); |
| 46 | + if (customerString.Length < 8) |
| 47 | + customerString = customerString.PadLeft(8, '0'); |
| 48 | + |
| 49 | + format = format.ToUpper(); |
| 50 | + switch (format) |
| 51 | + { |
| 52 | + case "G": |
| 53 | + return customerString.Substring(0, 1) + "-" + |
| 54 | + customerString.Substring(1, 5) + "-" + |
| 55 | + customerString.Substring(6); |
| 56 | + case "S": |
| 57 | + return customerString.Substring(0, 1) + "/" + |
| 58 | + customerString.Substring(1, 5) + "/" + |
| 59 | + customerString.Substring(6); |
| 60 | + case "P": |
| 61 | + return customerString.Substring(0, 1) + "." + |
| 62 | + customerString.Substring(1, 5) + "." + |
| 63 | + customerString.Substring(6); |
| 64 | + default: |
| 65 | + throw new FormatException( |
| 66 | + String.Format("The '{0}' format specifier is not supported.", format)); |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | +} |
| 71 | +// The example displays the following output: |
| 72 | +// 7-92031-59 |
| 73 | +// 7-92031-59 |
| 74 | +// 7/92031/59 |
| 75 | +// 7.92031.59 |
| 76 | +// The 'X' format specifier is not supported. |
| 77 | +// </Snippet2> |
0 commit comments