将 MemberExpression 转换为字符串

Convert MemberExpression to string

在下面的方法中,我尝试使用 List<string>().Contains() 方法创建一个表达式。

问题是我需要检查列表中是否存在的值不是字符串类型,因此我需要转换它。

private static Expression<Func<Books, bool>> GenerateListContainsExpression(string propertyName, List<string> values)
    {          
        var parameter = Expression.Parameter(typeof(Books), "b");
        var property = Expression.Property(parameter, propertyName);
        var method = typeof(List<string>).GetMethod("Contains");
        var comparison = Expression.Call(Expression.Constant(values), method, Expression.Constant(Expression.Convert(property, typeof(string))));

        return Expression.Lambda<Func<Books, bool>>(comparison, parameter);
    }

这给了我一个错误提示:

"No coercion operator is defined between types 'System.Nullable`1[System.Int32]' and 'System.String'."

不保证值的类型是int?

有什么办法吗?

您可以先对 属性 值调用 ToString。以下是如何执行此操作的示例:

private static Expression<Func<Books, bool>> GenerateListContainsExpression(
    string propertyName,
    List<string> values)
{
    var parameter = Expression.Parameter(typeof(Books), "b");
    var property = Expression.Property(parameter, propertyName);

    var contains_method = typeof(List<string>).GetMethod("Contains");

    var to_string_method = typeof(object).GetMethod("ToString");

    var contains_call = Expression.Call(
        Expression.Constant(values),
        contains_method,
        Expression.Call(property, to_string_method));

    return Expression.Lambda<Func<Books, bool>>(contains_call, parameter);
}