如何创建一个前pression树重新present'String.Contains("术语;)“在C#中?创建一个、术语、present、pression

2023-09-02 21:20:58 作者:很酷的女生,很酷的QQ名字

我刚开始使用前pression树,所以我希望这是有道理的。我想创建一个前pression树重新present:

I am just getting started with expression trees so I hope this makes sense. I am trying to create an expression tree to represent:

t => t.SomeProperty.Contains("stringValue");

到目前为止,我有:

So far I have got:

    private static Expression.Lambda<Func<string, bool>> GetContainsExpression<T>(string propertyName, string propertyValue)
    {
        var parameterExp = Expression.Parameter(typeof(T), "type");
        var propertyExp = Expression.Property(parameter, propertyName);
        var containsMethodExp = Expression.*SomeMemberReferenceFunction*("Contains", propertyExp) //this is where I got lost, obviously :)
        ...
        return Expression.Lambda<Func<string, bool>>(containsMethodExp, parameterExp); //then something like this
    }

我只是不知道如何引用String.Contains()方法。

I just don't know how to reference the String.Contains() method.

帮助AP preciated。

Help appreciated.

推荐答案

是这样的:

class Foo
{
    public string Bar { get; set; }
}
static void Main()
{
    var lambda = GetExpression<Foo>("Bar", "abc");
    Foo foo = new Foo { Bar = "aabca" };
    bool test = lambda.Compile()(foo);
}
static Expression<Func<T, bool>> GetExpression<T>(string propertyName, string propertyValue)
{
    var parameterExp = Expression.Parameter(typeof(T), "type");
    var propertyExp = Expression.Property(parameterExp, propertyName);
    MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
    var someValue = Expression.Constant(propertyValue, typeof(string));
    var containsMethodExp = Expression.Call(propertyExp, method, someValue);

    return Expression.Lambda<Func<T, bool>>(containsMethodExp, parameterExp);
}

您可能会发现这的帮助。