/// <summary>
/// 动态对象 必须继承 DynamicObject类
/// </summary>
public class DynamicObj : DynamicObject
{
/// <summary>
/// 键值对集合转动态对象
/// </summary>
/// <param name="dictionary"></param>
public DynamicObj(Dictionary<string, object> dictionary)
{
Dic = dictionary;
}
private Dictionary<string, object> Dic { get; set; }
/// <summary>
/// 设置动态对象属性值
/// </summary>
/// <param name="binder"></param>
/// <param name="value"></param>
/// <returns></returns>
public override bool TrySetMember(SetMemberBinder binder, object value)
{
Dic[binder.Name] = value;
return true;
}
/// <summary>
/// 获取动态对象属性值
/// </summary>
/// <param name="binder"></param>
/// <param name="result"></param>
/// <returns></returns>
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return Dic.TryGetValue(binder.Name, out result);
}
/// <summary>
/// 动态对象索引器
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public object this[string name]
{
get
{
return Dic[name];
}
set
{
Dic[name] = value;
}
}
}
//调用端
static void Main(string[] args)
{
Dictionary<string, object> dic=new Dictionary<string, object>();
dic.Add("Type",3);
dynamic dy = new DynamicObj(dic);
int type = dy.Type;
Console.WriteLine(type);
Console.ReadLine();
}