假设我有以下枚举.
[Flags] public enum Color { Red = 1,Blue = 2,Green = 4 }
现在,我想使用以下查询来查找红色衬衫.
Shirts.Where(x => (x.Color & Color.Red) != 0)
它工作正常,但当我尝试动态构造它:
var color= Expression.Constant(Color.Red); var property = Expression.Property(Expression.Parameter(typeof(Shirt)),"Color"); Expression.NotEqual(Expression.And(property,color),Expression.Constant(0));
我得到以下异常:
The binary operator And is not defined for the types ‘MyEnums.Color’
and ‘MyEnums.Color’.
我正在使用.NET 4.5
有什么想法吗?
解决方法
首先尝试使用
Expression.Convert
将颜色和属性转换为基础类型:
var color= Expression.Constant(Color.Red); var property = Expression.Property(Expression.Parameter(typeof(Shirt)),"Color"); var colorValue = Expression.Convert(color,Enum.GetUnderlyingType(typeof(Color))); var propertyValue = Expression.Convert(property,Enum.GetUnderlyingType(typeof(Color))); Expression.NotEqual(Expression.And(propertyValue,colorValue),Expression.Constant(0));