反射与编译以获得 MemberExpression 的值
如何在不使用 Compile() 而仅使用正常反射的情况下实现此目的?
var value = Expression.Lambda(memberExpression).Compile().DynamicInvoke();
我希望它能够在 iPhone (MonoTouch) 上运行,它不允许动态编译。
更新:这里有更多背景信息。这是我正在处理的代码:
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();
}
如您所见,if 块中的代码不使用运行时编译来获取值。我的目标是 else 块中的代码不使用运行时编译。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能。反射是元数据和非常有限的字节码检查的工具。它不允许突变或代码生成。从根本上讲,您在这里想要实现的是元数据和 IL 生成行为。反射不适用于这种情况。
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:
May be there are library with more complex expressions (new object creations etc.).