C# 4.0 新特性dynamic (待学习)

时间:2021-10-05 04:40:17

随便翻看了一下dynamic,在网上拷贝了一个例子,先贴出来等有空了再慢慢消化

static void Main(string[] args)
{
dynamic d = new MyDynamicObject();
d.Mytable = "ojlovecd";
d.ojlovecd = "wang";
Console.WriteLine(d.Mytable);//新加的字段,VS不会自动提示
Console.WriteLine(d.ojlovecd);//新加的字段,VS不会自动提示
Console.ReadKey();
}
/// <summary>
/// 需要先实现父类的两个虚方法
/// </summary>
class MyDynamicObject : System.Dynamic.DynamicObject
{
private Dictionary<string, object> dic = new Dictionary<string, object>();

public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
{
return dic.TryGetValue(binder.Name, out result) || base.TryGetMember(binder, out result);
}

public override bool TrySetMember(System.Dynamic.SetMemberBinder binder, object value)
{
if (dic.ContainsKey(binder.Name))
dic[binder.Name] = value;
else
dic.Add(binder.Name, value);
base.TrySetMember(binder, value);
return true;
}
}