using System;
using System.Collections.Generic;
using static Apewer.TextUtility;
#if !NET20
using System.Dynamic;
#endif
namespace Apewer
{
/// 对象字典模型。
[Serializable]
public class ObjectSet : ObjectSet
{
///
public ObjectSet(bool trimKey = false) : base(trimKey) { }
}
/// 字典模型。
[Serializable]
public partial class ObjectSet : IToJson
{
private Dictionary _origin;
private bool _trimkey = false;
private bool _locked = false;
/// 获取或设置字典内容。
public T this[string key] { get { return Get(key); } set { Set(key, value); } }
/// 获取字典。
internal Dictionary Origin { get { return _origin; } }
internal bool Locked { get { return _locked; } set { _locked = value; } }
internal bool TrimKey { get { return _trimkey; } set { _trimkey = value; } }
/// 构造函数。
public ObjectSet(bool trimKey = false)
{
_trimkey = trimKey;
_origin = new Dictionary();
}
private T Get(string key)
{
var contains = false;
return Get(key, ref contains);
}
private T Get(string key, ref bool contains)
{
var value = default(T);
if (key != null)
{
var k = _trimkey ? Trim(key) : key;
lock (_origin)
{
contains = _origin.ContainsKey(k);
if (contains) value = _origin[k];
}
}
return value;
}
private bool Set(string key, T value)
{
if (_locked) return false;
var success = false;
if (key != null)
{
var k = _trimkey ? Trim(key) : key;
lock (_origin)
{
if (_origin.ContainsKey(k)) _origin[k] = value;
else _origin.Add(k, value);
success = true;
}
}
return success;
}
/// 转换为 对象。
public Json ToJson() => Json.From(_origin);
/// 转换为 字符串。
public override string ToString()
{
var json = ToJson();
if (json == null) return null;
return json.ToString(true);
}
}
#if !NET20
/// 字典模型。
public partial class ObjectSet : DynamicObject
{
public override IEnumerable GetDynamicMemberNames()
{
return new List(_origin.Keys).ToArray();
}
///
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
var contains = false;
result = Get(binder.Name, ref contains);
return contains;
}
///
public override bool TrySetMember(SetMemberBinder binder, object value)
{
return Set(binder.Name, (T)value);
}
}
#endif
}