ExpandoObject :
动态的增删一个对象的属性,在低层库(例如ORM)中非常有用。
由于ExpandoObject实现了IDictionay<string, object>接口,常见的一种用法是,把expando转成dictionary,动态增加属性名和值[key,value],expando就达到了动态属性的目的。 示例代码(using System.Dynamic):
dynamic expando = new ExpandoObject();
expando.A = "a";
expando.B = 1;
// A,a
// B,1
IDictionary<string, object> dict = expando as IDictionary<string, object>;
foreach(var e in dict){
Console.WriteLine(e.Key + ","+ e.Value);
}
dict.Add("C", "c");
// c
Console.WriteLine(expando.C);
DynamicObject 类:
当需要track一个对象的属性被get或set时,这个类是很好的候选。 (通常出现在AOP的设计中,如果不打算使用AOP框架例如POSTSHARP的话),示例代码:
void Main()
{
dynamic obj = new MyDynaObject();
obj.A = "a";
obj.B = 1;
var a = obj.A;
// should print :
// tring to set member : A, with value : a
// tring to set member : B, with value : 1
// tring to get member : a
}
public class MyDynaObject : DynamicObject
{
// The inner dictionary.
Dictionary<string, object> dictionary
= new Dictionary<string, object>();
// This property returns the number of elements
// in the inner dictionary.
public int Count
{
get
{
return dictionary.Count;
}
}
// If you try to get a value of a property
// not defined in the class, this method is called.
public override bool TryGetMember(
GetMemberBinder binder, out object result)
{
// Converting the property name to lowercase
// so that property names become case-insensitive.
string name = binder.Name.ToLower();
Console.WriteLine("tring to get member : {0}", name);
// If the property name is found in a dictionary,
// set the result parameter to the property value and return true.
// Otherwise, return false.
return dictionary.TryGetValue(name, out result);
}
// If you try to set a value of a property that is
// not defined in the class, this method is called.
public override bool TrySetMember(
SetMemberBinder binder, object value)
{
// Converting the property name to lowercase
// so that property names become case-insensitive.
dictionary[binder.Name.ToLower()] = value;
Console.WriteLine("tring to set member : {0}, with value : {1}", binder.Name, value);
// You can always add a value to a dictionary,
// so this method always returns true.
return true;
}
}
// Define other methods and classes