Advertisement
Guest User

Untitled

a guest
Jun 28th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.92 KB | None | 0 0
  1.     static class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             var a = new C1();
  6.             Ext.SetValue(() => a.Msg, "TEST");
  7.             Debug.Assert(a.Msg == "TEST");
  8.         }
  9.     }
  10.  
  11.     class C1
  12.     {
  13.         public string Msg { get; set; }
  14.     }
  15.  
  16.     static class Ext
  17.     {
  18.         public static void SetValue<T>(Expression<Func<T>> expr, T value)
  19.         {
  20.             object obj;
  21.             MemberInfo mInfo = expr.GetMemberInfo<T>(out obj);
  22.  
  23.             FieldInfo fInfo = mInfo as FieldInfo;
  24.             PropertyInfo pInfo = mInfo as PropertyInfo;
  25.  
  26.             if (fInfo != null)
  27.                 fInfo.SetValue(obj, value);
  28.             else if (pInfo != null && pInfo.CanWrite)
  29.                 pInfo.SetValue(obj, value, null);
  30.         }
  31.  
  32.         public static MemberInfo GetMemberInfo<T>(this Expression<Func<T>> expr, out object obj)
  33.         {
  34.             if (expr == null)
  35.                 throw new ArgumentNullException("expr");
  36.  
  37.             var body = expr.Body as MemberExpression;
  38.  
  39.             if (body == null)
  40.             {
  41.                 var unaryExpr = expr.Body as UnaryExpression;
  42.  
  43.                 if (unaryExpr == null)
  44.                     throw new ArgumentException("'expr' should be either an unary expression or a member expression");
  45.  
  46.                 body = unaryExpr.Operand as MemberExpression;
  47.             }
  48.  
  49.             if (body == null)
  50.                 throw new ArgumentException("'expr' should be a member expression");
  51.  
  52.             LambdaExpression lambdaExpr = Expression.Lambda(body.Expression);
  53.             Delegate lambdaFunc = lambdaExpr.Compile();
  54.             obj = lambdaFunc.DynamicInvoke();
  55.  
  56.             MemberInfo mInfo = obj.GetType().GetMember(body.Member.Name).FirstOrDefault();
  57.  
  58.             if (mInfo == null)
  59.                 throw new InvalidOperationException("Member not found.");
  60.  
  61.             return mInfo;
  62.         }
  63.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement