(精華)2020年6月26日 C#類庫model DynamicModel

愚公搬程式碼發表於2020-06-26
using System.Collections.Generic;

namespace Coldairarrow.Util
{
    /// <summary>
    /// 動態資料模型類
    /// </summary>
    public class DynamicModel : Dictionary<string, object>
    {
        /// <summary>
        /// 索引器
        /// </summary>
        public new object this[string key]
        {
            get
            {
                return GetProperty(key);
            }
            set
            {
                AddProperty(key, value);
            }
        }

        /// <summary>
        /// 新增屬性
        /// </summary>
        /// <param name="key">屬性名</param>
        /// <param name="obj">屬性值</param>
        public void AddProperty(string key, object obj)
        {
            if (ContainsKey(key))
                base[key] = obj;
            else
                Add(key, obj);
        }

        /// <summary>
        /// 設定屬性值
        /// </summary>
        /// <param name="key">屬性名</param>
        /// <param name="obj">屬性值</param>
        public void SetProperty(string key, object obj)
        {
            if (ContainsKey(key))
                base[key] = obj;
            else
                Add(key, obj);
        }

        /// <summary>
        /// 獲取屬性值
        /// </summary>
        /// <param name="key">屬性名</param>
        /// <returns></returns>
        public object GetProperty(string key)
        {
            if (ContainsKey(key))
                return base[key];
            else
                return null;
        }
    }
}

相關文章