日期:2014-05-20  浏览次数:20750 次

linq 构建表达式问题
如何构建如下语句 s=> object.Equals(s.ID,myObject)

------解决方案--------------------
C# code
class Program
{
    static void Main(string[] args)
    {
        var user = new User { ID = "123" };
        
        var parameter = Expression.Parameter(typeof(User), "s");
        var memberAccessor = Expression.MakeMemberAccess(parameter, typeof(User).GetField("ID"));

        var constant = Expression.Constant("123", typeof(string));
        var call = Expression.Call(typeof(Object), "Equals", null, memberAccessor, constant);
        var lambda = Expression.Lambda<Func<User, bool>>(call, parameter);
        var exec = lambda.Compile();
        var result = exec(user);
        Console.WriteLine(result);
        Console.Read();
    }
}

class User
{
    public string ID;
}