C#DynamicObject和ExpandoObject用法

class Program
{
    static void Main(string[] args)
    {
        //dynamic v = new ExpandoObject();
        //v.Name = "123";
        //v.Value = "456";
        dynamic v = new MyDynamicObject();
        v.Name = "Name";
        v.Value = "Value";
        Console.WriteLine(v.Name);
        Console.ReadLine();
    }
}
    public class MyDynamicObject : DynamicObject
    {
        // The inner dictionary.
        private Dictionary _Values = new Dictionary();

        // Getting a property.
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            return _Values.TryGetValue(binder.Name, out result);
        }

        // Setting a property.
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            _Values[binder.Name] = value;
            return true;
        }

        public string ToJson()
        {
            return JsonConvert.SerializeObject(_Values);
        }

        public Dictionary Values
        {
            get { return this._Values; }
        }
    }
public class MyDynamicObjectCollection : IEnumerable
{
    private IList _Items = new ArrayList();

    public void Add(MyDynamicObject dynamicObject)
    {
        _Items.Add(dynamicObject.Values);
    }

    public string ToJson()
    {
        return JsonConvert.SerializeObject(_Items);
    }
        
    public IEnumerator GetEnumerator()
    {
        return _Items.GetEnumerator();
    }
}




你可能感兴趣的:(C#)