代码改变世界

.Net 4.0 ExpandoObject 使用(上)

2010-06-20 10:59  Henry Cui  阅读(4342)  评论(13编辑  收藏  举报

本篇文章中就ExpandoObject的基本使用进行一些demo。我们几乎都知道dynamic特性是.net 4.0中一个主要的新特性,而ExpandoObject正是这样的一个动态的类型。ExpandoObject允许我们在实例化之后在运行时进行成员的增加、删除。下面我们来看下基本的使用:

Adding Members

1)实例化

如果需要延迟绑定的话,我们需要用dynamic来定义ExpandpObject的实例化变量,关于dynamic的使用,估计大家都很清楚了。

            dynamic obj = new ExpandoObject();

2)增加属性成员

        [TestMethod]
        public void ExpandoObjectTest()
        {
            dynamic employee = new ExpandoObject();
            employee.FirstName = "Henry";
            employee.LastName = "Cui";
            employee.Age = 23;
            Console.WriteLine("Employee's name :{0} age:{1}",
                employee.FirstName + employee.LastName,
                employee.Age);
        }

 

测试的结果:

image

3)增加Method

在增加方法的时候,先把成员表现成delegate,先看一个没有参数的无返回值的方法:

        [TestMethod]
        public void ExpandoObjectTest()
        {
            dynamic employee = new ExpandoObject();
            employee.FirstName = "Henry";
            employee.LastName = "Cui";
            employee.Age = 23;
            employee.SayHello = (Action)(() => 
            {
                Console.WriteLine("{0} say \"Hello\" at {1}",
                    employee.FirstName+" "+employee.LastName,
                    DateTime.UtcNow.ToString());
            });
            employee.SayHello();
        }

在上面的示例中我们将SayHello定义成委托Action类型,并给了默认方法。

下面来看一个有参数、有返回值的:

[TestMethod]
        public void ExpandoObjectTest()
        {
            dynamic employee = new ExpandoObject();
            employee.FirstName = "Henry";
            employee.LastName = "Cui";
            employee.Age = 23;
            employee.SayHello = (Action)(() => 
            {
                Console.WriteLine("{0} say \"Hello\" at {1}",
                    employee.FirstName+" "+employee.LastName,
                    DateTime.UtcNow.ToString());
            });

            employee.GetSalary = (Func<int, decimal>)((month) => 
            {
                if (month > 8)
                    return 5000;
                return 4000;
            });
            Console.WriteLine("The employee's october salary is :${0}",
                employee.GetSalary(10).ToString());

        }

 

测试结果:

image

上面的例子中是段很简单的逻辑就是超过8月份的时候就返回$5000,呵呵。

4)增加Event

在实例中我们定义一个请假事件,员工请假就会上报给经理:

 [TestClass]
    public class DynamicTest
    {
        [TestMethod]
        public void ExpandoObjectTest()
        {
            dynamic employee = new ExpandoObject();
            employee.FirstName = "Henry";
            employee.LastName = "Cui";
            employee.Age = 23;
            employee.SayHello = (Action)(() => 
            {
                Console.WriteLine("{0} say \"Hello\" at {1}",
                    employee.FirstName+" "+employee.LastName,
                    DateTime.UtcNow.ToString());
            });

            employee.GetSalary = (Func<int, decimal>)((month) => 
            {
                if (month > 8)
                    return 5000;
                return 4000;
            });

            employee.AskForLeaveEvent = null;
            employee.AskForLeaveEvent += new EventHandler(OnEmployeeLeave);
            employee.AskForLeaveEvent(employee,new EventArgs());

        }

        public void OnEmployeeLeave(object sender, EventArgs e)
        {
            dynamic em = (dynamic)sender;
            Console.WriteLine("Report Manager:{0} is asking for leave", em.FirstName + " " + em.LastName);
        }

我们看下运行的结果:

image

 

Remove Members

其实ExpandoObject继承了IDictionary<String, Object>的接口,所以我们枚举出在运行时增加的那些成员.

1)枚举出已经存在的成员

我们就来枚举出刚才在employee中增加的成员们:

            foreach (var pro in (IDictionary<string, Object>)employee)
            {
                Console.WriteLine(pro.Key+" "+pro.Value);
            }

 

我们可以看到测试结果:

image

2)移除成员

其实我们还是利用了ExpandoObject实现了IDictionary接口去实现的,我们移除掉AskForLeaveEvent事件:

            ((IDictionary<string, object>)employee).Remove("AskForLeaveEvent");
            foreach (var pro in (IDictionary<string, Object>)employee)
            {
                Console.WriteLine(pro.Key+" "+pro.Value);
            }

我们看看运行的结果:

image

我们可以看到AskForLeaveEvent被移除了。

 

总结

本文中主要介绍了ExpandoObject的基本使用,我们发现真的有点动态语言的风味,写过javascript的人感觉会太别爽,呵呵。下文中会就ExpandoObject的原理以及一些扩展就行一些说明。

作者:Henllyee Cui
出处: http://henllyee.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明。