C# Dynamic动态对象

Posted 指间的徘徊

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 = 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动态对象的主要内容,如果未能解决你的问题,请参考以下文章

C#中Dynamic关键字

Json.net实现方便的Json转C#(dynamic动态类型)对象

Json.net实现方便的Json转C#(dynamic动态类型)对象

Json.net实现方便的Json转C#(dynamic动态类型)对象

将 XML 转换为动态 C# 对象

C# 使用dynamic类型来访问JObject对象