首页 > 解决方案 > 无法弄清楚 Expression.Call for Guid.Equals 进入谓词的语法

问题描述

尝试编写一种方法来动态查看通过 json 传递给我的数据(我没有严格输入)。我已经考虑了好几天了,我 100% 不确定语法,但我明白了这个概念。

任何人都可以帮我写这个,这样它就可以工作了吗?第一个“if”需要使用 StringComparer.OrdinalIgnoreCase 创建一个 Linq“包含”,第二个 if 需要创建一个 Guid.Equals 调用。

我觉得自己像个真正的白痴,但已经快 2 天了,而且没完没了的谷歌搜索。我什至阅读了 .Call 命令的界面,其中有大约 14 个,但我不知道哪个是做什么用的。我什至一次都无法让它工作。

    public static IQueryable<T> FilterDynamic<T>(this IQueryable<T> query, string fieldName, object values)
    {
        ParameterExpression param = Expression.Parameter(typeof(T), "e");
        MemberExpression prop = Expression.PropertyOrField(param, fieldName);

        // We use nullable guids in <T>, so i have to convert to actual guid
        UnaryExpression convertedExp = Expression.Convert(prop, prop.Type.GenericTypeArguments.Single());

        MethodCallExpression body;

        if (convertedExp.Type == typeof(string))
        {
            body = Expression.Call(typeof(Enumerable), "Contains", new[] {typeof(string)},
            Expression.Constant(values), prop);
        }
        
        
        if (convertedExp.Type == typeof(Guid))
        {
            MethodInfo methd = convertedExp.Type.GetMethod("Equals", BindingFlags.Instance | BindingFlags.Public, null,new Type[] { typeof(object) }, null);
            body = Expression.Call(prop.Type, "Equals", new[] {typeof(string)}, Expression.Constant(values), prop);    
        }

        // Other types need to just not do anything.
        
        Expression<Func<T, bool>> predicate = Expression.Lambda<Func<T, bool>>(body, param);
        return query.Where(predicate);
    }

我在第 35 行遇到的错误是No generic method 'Equals' on type 'System.Guid' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic.

编辑:我不得不像这样更改我的第二个 if 块: body = Expression.Call(convertedExp, methd, Expression.Constant(values));

我所有的答案都是通过阅读此代码找到的https://github.com/dotnet/corefx/blob/master/src/System.Linq.Expressions/src/System/Linq/Expressions/MethodCallExpression.cs

标签: c#expressionequalsguid

解决方案


推荐阅读