Differences between ExpandoObject, DynamicObject and dynamic

后端 未结 4 1790
抹茶落季
抹茶落季 2020-11-29 15:38

What are the differences between System.Dynamic.ExpandoObject, System.Dynamic.DynamicObject and dynamic?

In which situations d

4条回答
  •  既然无缘
    2020-11-29 16:22

    The above example of DynamicObject does not tell the difference clearly, because it's basically implementing the functionality which is already provided by ExpandoObject.

    In the two links mentioned below, it is very clear that with the help of DynamicObject, it is possible to preserve/change the actual type (XElement in the example used in below links) and better control on properties and methods.

    https://blogs.msdn.microsoft.com/csharpfaq/2009/09/30/dynamic-in-c-4-0-introducing-the-expandoobject/

    https://blogs.msdn.microsoft.com/csharpfaq/2009/10/19/dynamic-in-c-4-0-creating-wrappers-with-dynamicobject/

    public class DynamicXMLNode : DynamicObject    
    {    
        XElement node;
    
        public DynamicXMLNode(XElement node)    
        {    
            this.node = node;    
        }
    
        public DynamicXMLNode()    
        {    
        }
    
        public DynamicXMLNode(String name)    
        {    
            node = new XElement(name);    
        }
    
        public override bool TrySetMember(SetMemberBinder binder, object value)    
        {    
            XElement setNode = node.Element(binder.Name);
    
            if (setNode != null)    
                setNode.SetValue(value);    
            else    
            {    
                if (value.GetType() == typeof(DynamicXMLNode))    
                    node.Add(new XElement(binder.Name));    
                else    
                    node.Add(new XElement(binder.Name, value));    
            }
    
            return true;    
        }
    
        public override bool TryGetMember(GetMemberBinder binder, out object result)    
        {    
            XElement getNode = node.Element(binder.Name);
    
            if (getNode != null)    
            {    
                result = new DynamicXMLNode(getNode);    
                return true;    
            }    
            else    
            {    
                result = null;    
                return false;    
            }    
        }    
    }
    

提交回复
热议问题