首页 > 代码库 > C# Dynamic动态对象

C# Dynamic动态对象

1、ExpandoObject

 1  dynamic expObj = new ExpandoObject();
 2             expObj.FirstName = "Daffy";
 3             expObj.LastName = "Duck";
 4             Console.WriteLine(expObj.FirstName + " " + expObj.LastName);
 5             Func<DateTime, string> GetTomorrow = today => today.AddDays(1).ToShortDateString();
 6             expObj.GetTomorrowDate = GetTomorrow;
 7             Console.WriteLine("Tomorrow is {0}", expObj.GetTomorrowDate(DateTime.Now));
 8 
 9             expObj.Friends = new List<Person>();
10             expObj.Friends.Add(new Person() { FirstName = "Bob", LastName = "Jones" });
11             expObj.Friends.Add(new Person() { FirstName = "Robert", LastName = "Jones" });
12             expObj.Friends.Add(new Person() { FirstName = "Bobby", LastName = "Jones" });
13 
14             foreach (Person friend in expObj.Friends)
15             {
16                 Console.WriteLine(friend.FirstName + "  " + friend.LastName);
17             }

2、DynamicObject

 1 class CusDynamicObject : DynamicObject
 2     {
 3         Dictionary<string, object> _dynamicData = http://www.mamicode.com/new Dictionary<string, object>();
 4 
 5         public override bool TryGetMember(GetMemberBinder binder, out object result)
 6         {
 7             bool success = false;
 8             result = null;
 9             if (_dynamicData.ContainsKey(binder.Name))
10             {
11                 result = _dynamicData[binder.Name];
12                 success = true;
13             }
14             else
15                 result = "Property Not Found!";
16 
17             return success;
18         }
19 
20         public override bool TrySetMember(SetMemberBinder binder, object value)
21         {
22             _dynamicData[binder.Name] = value;
23             return true;
24         }
25 
26         public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
27         {
28             dynamic method = _dynamicData[binder.Name];
29             result = method((DateTime)args[0]);
30             return result != null;            
31         }
32 
33     }

 

C# Dynamic动态对象