拡張メソッドあれこれ
なんか使えそうな感じの拡張メソッドをいろいろ作ってみるテスト。
けど月並みなアイデアばかりで辟易だぞなもしorz
using System; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Extensions { public static class ObjectExtensions { public static int ToInt(this object o) { int result = 0; if (o == null) return result; try { result = int.Parse(o.ToString()); } catch { var p = from property in o.GetType().GetProperties() where Array.Exists(new[] { "Count", "Length" }, name => { return property.Name == name; }) select property; if (p.Count() != 0) return p.First().GetValue(o, null).ToInt(); } return result; } } public static class StringExtensions { public static string Times(this string s,int i) { string ret = string.Empty; for (int x = 0; x < i; x++) ret += s; return ret; } public static bool RegExIsMatch(this string s, string regex) { return new Regex(regex).IsMatch(s); } public static bool RegExIsMatch(this string s, string regex,int startat) { return new Regex(regex).IsMatch(s,startat); } public static Match RegExMatch(this string s, string regex) { return new Regex(regex).Match(s); } public static Match RegExMatch(this string s, string regex,int startat) { return new Regex(regex).Match(s, startat); } public static MatchCollection RegExMatches(this string s, string regex) { return new Regex(regex).Matches(s); } public static MatchCollection RegExMatches(this string s, string regex,int startat) { return new Regex(regex).Matches(s, startat); } public static bool IsNullOrEmpty(this string s) { return string.IsNullOrEmpty(s); } public static bool IsNotNullOrEmpty(this string s) { return !string.IsNullOrEmpty(s); } } public static class IntegerExtensions { public static IEnumerable<int> Times(this int i) { for (int x = 0; x < i; x++) yield return x; } public static IEnumerable<int?> Times(this int? i) { if (i == null) yield return 0; for (int x = 0; x < i; x++) yield return x; } } public static class IEnumerableExtensions { public static void ForEach(this IEnumerable source, Action<object> action) { foreach (object o in source) action(o); } public static void ForEach<T>(this IEnumerable source, Action<T> action) where T:class { foreach (object o in source) { T item = o as T; if (item != null) action((T)o); } } public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) { foreach (T item in source) action(item); } } }
IEnumerableExtensionsあたりは、標準装備してくれててもいいような気がしないこともない。
まあ自分で作っても大した手間じゃーないんだけど。