DLR之 ExpandoObject和DynamicObject的使用演示样例



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
原文地址:https://www.cnblogs.com/tlnshuju/p/7111651.html