首页 新闻 搜索 专区 学院

反射执行枚举 HasFlag 报错

0
悬赏园豆:10 [已解决问题] 解决于 2021-10-06 15:47
复制代码
/// <summary>
        /// HasFlag
        /// </summary>
        /// <typeparam name="TSource">数据类型</typeparam>
        /// <param name="pe">左侧表达式参数</param>
        /// <param name="property">属性</param>
        /// <param name="value"></param>
        /// <returns>表达式</returns>
        public static Expression HasFlag<TSource>(ParameterExpression pe, string property, object value)
        {
            MemberExpression member = pe.GetMemberExpression(property);
            if (Nullable.GetUnderlyingType(member.Type) != null && value != null)
            {
                member = Expression.Property(member, "Value");
            }
            CheckPropertyValueMismatch(member, Expression.Constant(value));
            var memberType = member.Member.MemberType == MemberTypes.Property ? (member.Member as PropertyInfo).PropertyType : (member.Member as FieldInfo).FieldType;
            var isNullType = IsNullableType(memberType);
            if ((isNullType && memberType?.GetGenericArguments()[0]?.IsEnum == true) || memberType.IsEnum)
                if (value?.ToString().Contains(",") ?? false)
                    return Expression.Call(member, typeof(Enum).GetMethod("HasFlag",new Type[]{typeof(Enum)}), Expression.Constant(value));
                else
                    return Expression.Equal(member, Expression.Constant(value));
            else
                return null;
        }
复制代码

表达式明明是支持位移枚举的HasFlag方法的,类似于list.AsQueryable().Where(m=>m.Gender.HasFlag(input.Gender)).ToList(),不懂为啥这里程序报不支持 , 具体错误如下:

Expression of type 'System.Linq.Expressions.Tests.EnumGender' cannot be used for parameter of type 'System.Enum' of method 'Boolean HasFlag(System.Enum)' (Parameter 'arg0')

noert的主页 noert | 初学一级 | 园豆:37
提问于:2021-10-06 10:56
< >
分享
最佳答案
0

return Expression.Call(member, typeof(Enum).GetMethod("HasFlag", new[] { typeof(Enum) }), Expression.Constant(value, typeof(Enum)));
值要指定一下类型

noert | 初学一级 |园豆:37 | 2021-10-06 11:33
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册