views:

578

answers:

1

How can I achieve this without using Compile() but just with normal reflection?

var value = Expression.Lambda(memberExpression).Compile().DynamicInvoke();

I want this to be able to run on an IPhone (MonoTouch), which does not allow dynamic compiling.

UPDATE: Here is more context. This is the code I am working on:

if (expression.Expression is ConstantExpression)
{
 var constantExpression = (ConstantExpression)expression.Expression;
 var fieldInfo = constantExpression.Value.GetType().GetField(expression.Member.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
 if (fieldInfo != null)
 {
  return fieldInfo.GetValue(constantExpression.Value);
 }
 {
  var propertyInfo = constantExpression.Value.GetType().GetProperty(expression.Member.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
  if (propertyInfo != null)
  {
   return propertyInfo.GetValue(constantExpression.Value, null);
  }
 }
}
else
{
 return Expression.Lambda(expression.Expression).Compile().DynamicInvoke();
}

As you can see, the code in the if block uses no runtime compilation to obtain the value. My goal is that the code in the in the else block not use runtime compilation either.

+3  A: 

You cannot. Reflection is tool for metadata and very limited byte code inspection. It does not allow for mutation or code generation. Fundamentally what you are trying to achieve here is a metadata and IL generation act. Reflection will not work for this scenario.

JaredPar
What you say is not totally correct. I know, for example, that in the case that memberExpression.Expression is a ConstantExpression you can get its value by reflecting on the constant expression's Value property. My problem is that when it's not a ConstantExpression, I cannot figure how to get a handle on the instance that holds the value.
Tim Scott
If it's not a constant, you will need to execute it to get the result. Thus the compile.
Gregory