Reflection vs. Compile To Get The Value Of MemberExpression
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 propertyInf开发者_开发知识库o.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.
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.
I have some more specific cases:
private static object ExtractValue(Expression expression)
{
if (expression == null)
{
return null;
}
var ce = expression as ConstantExpression;
if (ce != null)
{
return ce.Value;
}
var ma = expression as MemberExpression;
if (ma != null)
{
var se = ma.Expression;
object val = null;
if (se != null)
{
val = ExtractValue(se);
}
var fi = ma.Member as FieldInfo;
if (fi != null)
{
return fi.GetValue(val);
}
else
{
var pi = ma.Member as PropertyInfo;
if (pi != null)
{
return pi.GetValue(val);
}
}
}
var mce = expression as MethodCallExpression;
if (mce != null)
{
return mce.Method.Invoke(ExtractValue(mce.Object), mce.Arguments.Select(ExtractValue).ToArray());
}
var le = expression as LambdaExpression;
if (le != null)
{
if (le.Parameters.Count == 0)
{
return ExtractValue(le.Body);
}
else
{
return le.Compile().DynamicInvoke();
}
}
var dynamicInvoke = Expression.Lambda(expression).Compile().DynamicInvoke();
return dynamicInvoke;
}
May be there are library with more complex expressions (new object creations etc.).
精彩评论