请参阅下面代码中的注释。
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
var myType = new MyType();
myType.p = "Some Value";
var compareMethod = DoWork<MyType>("Some Value", "p");
var isEqual = compareMethod(myType);
}
public static Func<T, bool> DoWork<T>(object val, string prop)
{
//The code below will construct an expression like 'p => p.prop == value'
//Creates the parameter part of an expression. So the 'p =>' part of the expression.
ParameterExpression pe = Expression.Parameter(typeof(T), "p");
//Get access to the property info, like the getter and setter.
PropertyInfo pi = typeof(T).GetProperty(prop);
// // Constructs the part of the expression where the member is referenced, so the 'p.prop' part.
MemberExpression me = Expression.MakeMemberAccess(pe, pi);
//Creates the constant part of the expression, the 'value' part.
ConstantExpression ce = Expression.Constant(val);
//creates the comparison part '==' of the expression.
//So this requires the left and right side of 'left == right'
//Which is the property and the constant value.
//So 'p.prop == value'
BinaryExpression be = Expression.Equal(me, ce);
//Puts the 'p => ' and 'p.prop == value' parts of the expression together to form the
//complete lambda
//Compile it to have an executable method according to the same signature, as
//specified with Func<T, bool>, so you put a class in of type T and
//the 'p.prop == value' is evaluated, and the result is returned.
return Expression.Lambda<Func<T, bool>>(be, pe).Compile();
}
}
public class MyType
{
public string p { get; set; }
}
}
也就是说,我认为这是一种仅比较的复杂方式。您想到的用例可能会证明这一点。您是否使用 LINQ-to-SQL 或必须使用表达式?根据我的经验,在大多数情况下,您可以使用 Funcs 和接口来解决这个问题,在 3rd 方类的情况下,可能与包装类结合使用。代码本身可能会在内存中创建一些 MSIL,然后使用 CLR 的即时编译器在内存中将其编译为本机代码,其中内存的分配被标记为可执行。我不知道它是如何工作的,这只是一个猜测。有关如何为不同目的标记内存分配的更多信息,请参阅内存保护常量。