C# 动态类添加属性

1.定义JsonDataObject 

public sealed class JsonDataObject : DynamicObject
{
    private readonly Dictionary<string, object> _properties;
    public JsonDataObject(Dictionary<string, object> properties)
    {
        _properties = properties;
    }
    public override IEnumerable<string> GetDynamicMemberNames()
    {
        return _properties.Keys;
    }
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        if (_properties.ContainsKey(binder.Name))
        {
            result = _properties[binder.Name];
            return true;
        }
        else
        {
            result = null;
            return false;
        }
    }
    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        if (_properties.ContainsKey(binder.Name))
        {
            _properties[binder.Name] = value;
            return true;
        }
        else
        {
            return false;
        }
    }
}

 2.调用

Dictionary<string, object> dic = new Dictionary<string, object>
{
    { "key1", "value1" },
    { "key2", "value2" },
    { "key3", "value3" },
    { "key4", "value4" }
};
dynamic result = new JsonDataObject(dic);

 result即为需要的结果。

posted @ 2023-11-21 17:12  新*  阅读(743)  评论(0编辑  收藏  举报