c# dynamic实现动态实体,不用定义实体就能序列化为标准json

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;

namespace SelfDynamicObj
{
    public delegate object DeleDynamic(dynamic sender, params object[] pramas);
    public class DynObj : DynamicObject
    {
        public Dictionary<string, object> _values;

        public DynObj()
        {
            _values = new Dictionary<string, object>();
        }

        public object GetPropertyValue(string propertyName)
        {
            if (_values.ContainsKey(propertyName) == true)
            {
                return _values[propertyName];
            }
            return null;
        }

        public void SetPropertyValue(string propertyName, object value)
        {
            if (_values.ContainsKey(propertyName) == true)
            {
                _values[propertyName] = value;
            }
            else
            {
                _values.Add(propertyName, value);
            }

        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = GetPropertyValue(binder.Name);
            return result == null ? false : true;
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            SetPropertyValue(binder.Name, value);
            return true;
        }

        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            var deleObj = GetPropertyValue(binder.Name) as DelegateObj;
            if (deleObj == null || deleObj.CallMethod == null)
            {
                result = null;
                return false;
            }
            result = deleObj.CallMethod(this, args);
            return true;
        }

        public override bool TryInvoke(InvokeBinder binder, object[] args, out object result)
        {
            return base.TryInvoke(binder, args, out result);
        }

    }


    public class DelegateObj
    {
        private DeleDynamic _deleDynamic;

        public DeleDynamic CallMethod
        {
            get { return _deleDynamic; }
        }

        public DelegateObj(DeleDynamic deleDynamic)
        {
            this._deleDynamic = deleDynamic;
        }

        public static DelegateObj Function(DeleDynamic deleDynamic)
        {
            return new DelegateObj(deleDynamic);
        }
    }
}

使用如下:

List<string> names = new List<string>() { "a00", "b00", "c00", "d00" };



dynamic obj = new DynObj();
obj.date = "2019-02-26";
obj.stories = names;
string result0 = JsonConvert.SerializeObject(obj._values);

 

序列化后的结果如下:

{
"date": "2019-02-26",
"stories": ["a00", "b00", "c00", "d00"]
}


c# dynamic实现动态实体,不用定义实体就能序列化为标准json

上一篇:Delphi 动态链接库编程


下一篇:c#实现生成PDF的底层方法