using Apewer.Internals;
using System;
using System.Collections.Generic;
#if !NET20
using System.Dynamic;
#endif
namespace Apewer
{
/// 对象字典模型。
[Serializable]
public class ObjectSet : ObjectSet
{
///
public ObjectSet(bool autoTrim)
{
AutoTrim = autoTrim;
}
///
public ObjectSet() { }
}
/// 字典模型。
[Serializable]
public partial class ObjectSet // where T : class
{
[NonSerialized]
private readonly T Default = default(T);
private Dictionary _origin;
private bool _autotrim = 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 AutoTrim { get { return _autotrim; } set { _autotrim = value; } }
/// 构造函数。
public ObjectSet()
{
_origin = new Dictionary();
}
/// 构造函数。
public ObjectSet(bool autoTrim)
{
_autotrim = autoTrim;
_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 = _autotrim ? TextModifier.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 = _autotrim ? TextModifier.Trim(key) : key;
lock (_origin)
{
if (_origin.ContainsKey(k))
{
_origin[k] = value;
}
else
{
_origin.Add(k, value);
}
success = true;
}
}
return success;
}
}
#if !NET20
/// 字典模型。
public partial class ObjectSet : DynamicObject
{
///
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
}