zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    django 中 slice 和 truncatewords 不同用法???
    js如何获取到select的option值???
    MySQL的btree索引和hash索引的区别
    Python3之Django Web框架中间件???
    2019.07.25考试报告
    2019.07.19考试报告
    2019.07.18考试报告
    2019.07.16考试报告
    2019.07.12考试报告
    ELK+Kafka
  • 原文地址:https://www.cnblogs.com/farmer-y/p/5978268.html
Copyright © 2011-2022 走看看