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 }