炫意html5
最早CSS3和HTML5移动技术网站之一

反射执行枚举 HasFlag 报错

复制代码
/// <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’)

回答

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

炫意HTML5 » 反射执行枚举 HasFlag 报错

Java基础教程Android基础教程