DLR之 ExpandoObject和DynamicObject的使用演示样例
2024-08-31 12:08:57
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
最新文章
- 彻底删除MySQL
- 2016 Multi-University Training Contest 6
- Atitit 发帖机系列(8) &#160;词法分析器v5 版本新特性说明)
- Windows系统结合MinGW搭建软件开发环境
- application 网站计数器
- The sound of silence引发的关于互联网以及教育的利弊思考
- Html5 js FileReader接口
- php中有用插件集合
- LPC2478的硬件IIC使用
- C++ Primer 5 CH1 开始
- 道可道,非常道——详解promise
- Asp.net core 学习笔记 (library)
- Linux umask
- download 属性
- Java代理:静态代理、动态代理
- Android 后台发送邮件 (收集应用异常信息+Demo代码)
- Kafka usecase
- 前端开发组件化设计vue,react,angular原则漫谈
- 快速搭建简单的LBS程序——地图服务
- WCF与WPF