文字列が数字のみで構成されているかどうかを取得する拡張メソッドIsNumberOnlyです。
拡張メソッド定義
using System; using System.Linq; namespace Extensions { static class StringExtensions { /// <summary> /// 文字列が数字のみで構成されているかどうかを示す値を取得します。 /// </summary> /// <param name="self">System.Stringのインスタンス。</param> /// <returns>文字列が数字のみで構成されている場合はtrue。数字以外を含む場合はfalse。</returns> public static bool IsNumberOnly(this string self) { const string Numbers = "0123456789"; if (string.IsNullOrEmpty(self)) { return true; } return !self.Except(Numbers).Any(); } } }
テスト
using System; namespace Extensions { class Program { static void Main(string[] args) { string hoge1 = "100"; Console.WriteLine(hoge1.IsNumberOnly()); // True string hoge2 = "10a"; Console.WriteLine(hoge2.IsNumberOnly()); // False string hoge3 = ""; Console.WriteLine(hoge3.IsNumberOnly()); // True string hoge4 = null; Console.WriteLine(hoge4.IsNumberOnly()); // True string hoge5 = " "; Console.WriteLine(hoge5.IsNumberOnly()); // False Console.ReadKey(); } } }