コード例 #1
0
        public static void WalkObject(object obj, IObjectWalker objectWalker, int depth)
        {
            Action <IObjectWalker, object, string, int> parseObject = null;

            objectWalker.OnStart(obj.GetType().Name);
            parseObject = (walker, o, txt, dep) =>
            {
                if (dep-- == 0)
                {
                    return;
                }

                if (o == null)
                {
                    walker.OnField(ParseResult.CreateForField("Unknown", txt, "null"));
                    return;
                }
                var t = o.GetType();
                if (t.IsValueType)
                {
                    walker.OnField(ParseResult.CreateForField(t.Name, txt, o.ToString()));
                }
                else
                {
                    if (t == typeof(string))
                    {
                        walker.OnField(ParseResult.CreateForField(t.Name, txt, (string)o));
                    }
                    else
                    {
                        walker.OnBeginContainer(ParseResult.CreateForContainer(t.Name, txt));
                        if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary <,>))
                        {
                            var dict = (IDictionary)o;
                            foreach (DictionaryEntry entry in dict)
                            {
                                parseObject(walker, new KeyValue {
                                    Key = entry.Key, Value = entry.Value
                                }, "", dep);
                            }
                        }
                        else if (t.IsArray || t.IsGenericType && _genericDefinitions.Contains(t.GetGenericTypeDefinition()))
                        {
                            foreach (var item in (IEnumerable)o)
                            {
                                parseObject(walker, item, "", dep);
                            }
                        }
                        else
                        {
                            var properties = o.GetType().GetProperties().Where(p => p.CanRead);
                            foreach (PropertyInfo property in properties)
                            {
                                object val  = property.GetValue(o, null);
                                string name = property.Name;
                                parseObject(objectWalker, val, name, dep);
                            }
                        }
                        walker.OnEndContainer();
                    }
                }
            };

            parseObject(objectWalker, obj, null, depth);
            objectWalker.OnFinish();
        }