štvrtok 12. januára 2012

Generic object dumper with optimized performance

I have actually created this helper class, using for generating logs.
It's using caching and reflection, so the performance impact shouldn't be very high.

Maybe you''ll find this code snippet useful.

/// <summary>
/// Use only  for primitive objects (next version is planning)
/// </summary>
public static class ObjectDumper
    {
        private static Dictionary<Type, System.Reflection.PropertyInfo[]> properties;


         static ObjectDumper()
        {
            properties = new Dictionary<Type, System.Reflection.PropertyInfo[]>();
        }

        public static string DumpDictionary<T, U>(Dictionary<T, U> dictionary, string format)
        {
            StringBuilder result = new StringBuilder();

            foreach (KeyValuePair<T, U> keyVal in dictionary)
            {
                result.AppendFormat(format, keyVal.Key, keyVal.Value);
            }

            return result.ToString();
        }

        /// <summary>
        /// Generic object dumper with optimized performance
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        public static string DumpObject<T>(T obj)
        {
            StringBuilder result = new StringBuilder();
            System.Reflection.PropertyInfo[] pi = GetPropertyInfo(typeof(T));
            result.Append("\n");

            object value;
            for (int i = 0; i < pi.Length; i++)
            {
                value = pi[i].GetValue(obj, null);

                if (value == null)
                    result.AppendFormat("\n{0} = NULL", pi[i].Name);
                else
                {
                    if(pi[i].DeclaringType.IsArray)
                        result.AppendFormat("\n{0} = is array...", pi[i].Name);
                    else
                        result.AppendFormat("\n{0} = {1}", pi[i].Name, value.ToString());
                }
            }

            return result.ToString();
        }

        /// <summary>
        /// Caching logic
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        private static System.Reflection.PropertyInfo[] GetPropertyInfo(Type t)
        {
            System.Reflection.PropertyInfo[] result = null;
            if (properties.TryGetValue(t, out result) == false)
            {
                result = t.GetProperties();
                properties.Add(t, result);
            }

            return result;
        }
   
    }

Žiadne komentáre:

Zverejnenie komentára