C#DynamicObject和ExpandoObject用法

風之_訴發表於2017-10-12
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<string, object> _Values = new Dictionary<string, object>();

        // 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<string, object> 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();
    }
}




相關文章