首页 新闻 会员 周边 捐助

.net超高手进/动态类型疑问

0
悬赏园豆:5 [已关闭问题] 关闭于 2012-12-15 13:28

 class Program
    {
        static void Main(string[] args)
        {
            string xml = @"<root>
                          <books>
                             <book>
                                 <author>TOM</author>
                                 <title>E.G.Tttle</title>
                                 <price>20.5</price>
                               </book>
                               <book>
                                 <author>JERRY</author>
                                 <title>E.G.Tttle</title>
                                 <price>10.2</price>
                               </book>
                            </books>
                        </root>";
            dynamic dx = new DynamicXml(xml);
            foreach (dynamic b in dx.books.book)
            {
                Console.WriteLine("author='{0}'",b.author.Value);
            }
            Console.ReadLine();
        }
    }

    public class DynamicXml : DynamicObject, IEnumerable
    {
        private readonly List<XElement> _elements;

        public DynamicXml(string text)
        {
            var doc = XDocument.Parse(text);
            _elements = new List<XElement> { doc.Root };
        }

        protected DynamicXml(XElement element)
        {
            _elements = new List<XElement> { element };
        }

        protected DynamicXml(IEnumerable<XElement> elements)
        {
            _elements = new List<XElement>(elements);
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = null;
            if (binder.Name == "Value")
                result = _elements[0].Value;
            else if (binder.Name == "Count")
                result = _elements.Count;
            else
            {
                var attr = _elements[0].Attribute
                    (
                       XName.Get(binder.Name)
                    );
                if (attr != null)
                {
                    result = attr;
                }
                else
                {
                    var items = _elements.Descendants(
                           XName.Get(binder.Name)
                        );
                    if (items == null || items.Count() == 0)
                        return false;
                    result = new DynamicXml(items);
                }
            }
            return true;
        }

        public IEnumerator GetEnumerator()
        {
            foreach (var element in _elements)
            {
                yield return new DynamicXml(element);
            }
        }
    }

网上 的一段动态类型的实例。。请问高手为什么foreach (dynamic b in dx.books.book)能对dx.books.book进行循环操作。。??不是只能对dx嘛??请高手解释下这段代码!!!!!!

彬彬@科比的主页 彬彬@科比 | 初学一级 | 园豆:43
提问于:2012-12-15 13:23
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册