잊지 않겠습니다.

'ToString'에 해당되는 글 1건

  1. 2010.10.21 Class의 모든 Property를 Xml 값으로 표현하기.
PropertyInfo를 이용해서 간단히 슥삭. 너무나 편하게 debuging할 수 있는 방법이라서 자주 사용하기도 하고, 긁어서 그냥 넣어주면 편해서 올려둔다. 기본적으로 Property Invoke를 이용해서 각 값을 얻어내고, 그 값을 표시하는 방법인데... 이모저모로 편하구. 



01.public override string ToString()
02.{
03.    StringBuilder sb = new StringBuilder();
04.    sb.AppendLine(string.Format("<{0}>", GetType().Name));
05.    foreach(PropertyInfo property in GetType().GetProperties())
06.    {
07.        string propertyName = property.Name;
08.        object value = property.GetValue(this, null);
09.        if(value != null)
10.        {
11.            if(value is IEnumerable && !(value is string))
12.            {
13.                sb.AppendLine(string.Format("<{0}>", propertyName));
14.                IEnumerator enumerator = ((IEnumerable)value).GetEnumerator();
15.                while(enumerator.MoveNext())
16.                {
17.                    sb.AppendLine(enumerator.Current.ToString());
18.                }
19.                sb.AppendLine(string.Format("<!--{0}-->", propertyName));
20.            }
21.            else
22.            {
23.                sb.AppendLine(string.Format("<{0}>{1}<!--{0}-->", propertyName, value.ToString()));
24.            }
25.        }
26.    }
27.    sb.Append(string.Format("<!--{0}-->", GetType().Name));
28.    return sb.ToString();
29.}
Posted by Y2K
,