FizzBuzz 別解
ふと思いついたので別解を書いてみた。
using System; using System.Globarization; public class FizzBuzzFormatInfo : IFormatProvider, ICustomFormatter { public object GetFormat(Type formatType) { if (formatType == typeof(ICustomFormatter)) { return this; } return CultureInfo.CurrentCulture.GetFormat(formatType); } public string Format(string format, object arg, IFormatProvider formatProvider) { if (format == null) { return String.Format("{0}", arg); } var data = (int)arg; return ((data % 15 == 0) ? "FizzBuzz" : (data % 3 == 0) ? "Fizz" : (data % 5 == 0) ? "Buzz" : data.ToString()); } } class Foo { static void Main() { var formatInfo = new FizzBuzzFormatInfo(); for (var i = 1; i <= 100; i++) { Console.WriteLine(String.Format(formatInfo, "{0:FB}", i)); } Console.ReadLine(); } }
……カスタムフォーマットなんて初めてまともに使った気がする。<まともじゃない