以下メモ書きです。
javaやってたとき、よくcommons-langのToStringBuilder.reflectionToString()メソッドに
お世話になってました。
自分でサンプル作っているときにいちいちToString()定義するのが面倒くさいので
reflectionToStringチックなものを作成。
こんな感じ。objectクラスの拡張メソッドとしときました。
public static class ObjectExtensions{ public static string ReflectionToString(this object o){ if(o == null){ return ""; } List<string> l = new List<string>(); foreach(FieldInfo fi in o.GetType().GetFields()){ l.Add(string.Format("{0}:{1}", fi.Name, fi.GetValue(o))); } foreach(PropertyInfo pi in o.GetType().GetProperties()){ l.Add(string.Format("{0}:{1}", pi.Name, pi.GetValue(o, null))); } StringBuilder sb = new StringBuilder(o.GetType().Name); sb.Append(string.Format(": [{0}]", string.Join(",", l.ToArray()))); return sb.ToString(); } }
ついでに、.net 3.5の機能を無理やりつかってワンライナーチックにしてみました。
単にLINQちょっと使ってみたかっただけです。
こんなん実務で見たらしばかれますね。w
public static class ObjectExtensions{ public static string ReflectionToString(this object o){ return (o == null) ? "" : new StringBuilder(o.GetType().Name).Append( string.Format( ": [{0}]", string.Join( ", ", ( from fi in o.GetType().GetFields() select new{Name=fi.Name, Value=fi.GetValue(o)} ).Union( from pi in o.GetType().GetProperties() select new{Name=pi.Name, Value=pi.GetValue(o, null)} ).ToList().ConvertAll( elem => { return string.Format("{0}:{1}", elem.Name, elem.Value); } ).ToArray() ) ) ).ToString(); } }
以下のようにして使えます。
class Demo{ public string Field1 = "hoge"; public string Prop1{ get; set; } public string Prop2{ get; set; } public override string ToString(){ return ((object) this).ReflectionToString(); } // // EntryPoint // static void Main(){ Console.WriteLine(new Demo{Prop1="hehe", Prop2="fuga"}); } }