Example #1
0
        public static void TestRef(People people)
        {
            PropertyInfo propertyInfo = people.GetType().GetProperty("Name");

            propertyInfo.SetValue(people, "sl");
            var name = propertyInfo.GetValue(people);
        }
Example #2
0
        public static void TestExpression(People people)
        {
            PropertyInfo propertyInfo = people.GetType().GetProperty("Name");


            ParameterExpression param = Expression.Parameter(typeof(People), "param");
            Expression          GetPropertyValueExp = Expression.Lambda(Expression.Property(param, "Name"), param);
            Expression <Func <People, String> > GetPropertyValueLambda = (Expression <Func <People, String> >)GetPropertyValueExp;// (dog)=>dog.Name;
            ParameterExpression  paramo = Expression.Parameter(typeof(People), "param");
            ParameterExpression  parami = Expression.Parameter(typeof(String), "newvalue");
            MethodCallExpression MethodCallSetterOfProperty = Expression.Call(paramo, propertyInfo.GetSetMethod(), parami);
            Expression           SetPropertyValueExp        = Expression.Lambda(MethodCallSetterOfProperty, paramo, parami);
            Expression <Action <People, String> > SetPropertyValueLambda = (Expression <Action <People, String> >)SetPropertyValueExp;//(dog,newvalue)=>dog.Name=newvalue;

            //创建了属性Name的Get方法表达式和Set方法表达式,当然只是最简单的
            Func <People, String>   Getter = GetPropertyValueLambda.Compile();
            Action <People, String> Setter = SetPropertyValueLambda.Compile();

            Setter.Invoke(people, "sl");
            var name = Getter.Invoke(people);
        }