当你“关闭”一个局部变量时,会生成一个隐藏类。您在 中看到的ConstantExpression
是对这个隐藏类的一个实例的引用。
这个:
public void MyWhere<T>(Expression<Func<T, bool>> predicate)
{
}
public void M()
{
List<string> Indexes2 = new List<string>();
Indexes2.Add("abc");
MyWhere<String>(a => Indexes2.Contains(a));
}
编译为
[CompilerGenerated]
private sealed class <>c__DisplayClass1_0
{
public List<string> Indexes2;
}
public void MyWhere<T>(Expression<Func<T, bool>> predicate)
{
}
public void M()
{
<>c__DisplayClass1_0 <>c__DisplayClass1_ = new <>c__DisplayClass1_0();
<>c__DisplayClass1_.Indexes2 = new List<string>();
<>c__DisplayClass1_.Indexes2.Add("abc");
ParameterExpression parameterExpression = Expression.Parameter(typeof(string), "a");
MemberExpression instance = Expression.Field(Expression.Constant(<>c__DisplayClass1_, typeof(<>c__DisplayClass1_0)), FieldInfo.GetFieldFromHandle((RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/));
MethodInfo method = (MethodInfo)MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/, typeof(List<string>).TypeHandle);
Expression[] array = new Expression[1];
array[0] = parameterExpression;
MethodCallExpression body = Expression.Call(instance, method, array);
ParameterExpression[] array2 = new ParameterExpression[1];
array2[0] = parameterExpression;
MyWhere(Expression.Lambda<Func<string, bool>>(body, array2));
}
(见夏普实验室)
有趣的部分是private sealed class <>c__DisplayClass1_0
和Expression.Constant(<>c__DisplayClass1_, typeof(<>c__DisplayClass1_0))
。
这个隐藏的类是隐藏的。您只能通过反射与它进行交互。
您的问题并不能以简单的方式真正解决。对于给出的具体示例:
public static void MyWhere<T>(Expression<Func<T, bool>> predicate)
{
var body = predicate.Body;
// .Contains(...)
var contains = body as MethodCallExpression;
// Indexes2
var field = contains.Object;
// Need boxing only for value types
var boxIfNecessary = field.Type.IsValueType ? (Expression)Expression.Convert(field, typeof(object)) : field;
var lambda = Expression.Lambda<Func<object>>(boxIfNecessary);
var compiled = lambda.Compile();
// Indexes of type List<string>()
var value = compiled();
}
例如这个:
MyWhere<string>(a => Enumerable.Contains(Indexes2, a));
会破坏我给出的代码。