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     }
  • 相关阅读:
    清除图片周围的空白区域
    试题识别与生成
    需要继续研究
    工作中的必要举措
    教学云平台要求的硬件配置
    处理程序安装部署标准流程
    Node.js 回调函数
    git 学习
    在 Selenium 中让 PhantomJS 执行它的 API
    RF常用库简介(robotframework)
  • 原文地址:https://www.cnblogs.com/farmer-y/p/5978268.html
Copyright © 2011-2022 走看看