• .NET Lamda 给匿名属性赋值


     1 var _list = new { Name = "111111", Value = "AAAAA" };
     2 _list.Set();
     3 var myAnonInstance = new
     4 {
     5 FirstField = "Hello",
     6 AnotherField = 30,
     7 a = new { a = 111 }
     8 };
     9 Console.WriteLine(myAnonInstance);
    10 myAnonInstance.a.Set(o => o.a, 2222);
    11 myAnonInstance
    12     .Set(x => x.FirstField, "Hello SO")
    13     .Set(x => x.AnotherField, 42);
    14 Console.WriteLine(myAnonInstance);
    15 
    16 public static class AnonymousObjectMutator
    17 {
    18     private const BindingFlags FieldFlags = BindingFlags.NonPublic | BindingFlags.Instance;
    19     private static readonly string[] BackingFieldFormats = { "<{0}>i__Field", "<{0}>" };
    20 
    21     public static T Set<T, TProperty>(this T instance, Expression<Func<T, TProperty>> propExpression, TProperty newValue) where T : class
    22     {
    23         var pi = (propExpression.Body as MemberExpression).Member;
    24         var backingFieldNames = BackingFieldFormats.Select(x => string.Format(x, pi.Name)).ToList();
    25         var fi = typeof(T)
    26             .GetFields(FieldFlags)
    27             .FirstOrDefault(f => backingFieldNames.Contains(f.Name));
    28         if (fi == null)
    29         {
    30             GetDynamicClassBydt("", "bb");
    31             //throw new NotSupportedException(string.Format("Cannot find backing field for {0}", pi.Name));
    32         }
    33         else
    34         {
    35             fi.SetValue(instance, newValue);
    36         }
    37         return instance;
    38     }
    39 
    40     /// <summary>
    41     /// 使用dynamic根据DataTable的列名自动添加属性并赋值
    42     /// </summary>
    43     /// <param name="dt"></param>
    44     /// <returns></returns> 
    45     public static Object GetDynamicClassBydt(string file, string vl)
    46     {
    47         dynamic d = new System.Dynamic.ExpandoObject();
    48         //创建属性,并赋值。
    49         (d as System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<string, object>>).Add(new System.Collections.Generic.KeyValuePair<string, object>(file, vl));
    50 
    51         return d;
    52     }
    53 }
    View Code
  • 相关阅读:
    设计模式总结
    字符编码小结
    搞定java.io
    将代码托管到GitHub上
    linuxlinux 路由表设置 之 route 指令详解 路由表设置 之 route 指令详解
    linux子系统的初始化_subsys_initcall()
    Linux系统目录结构介绍
    EtherType :以太网类型字段及值
    socket编程原理
    linux下的网络接口和网络桥接
  • 原文地址:https://www.cnblogs.com/Early/p/15871774.html
Copyright © 2020-2023  润新知