2013-03-27 27 views
6

Giả sử tôi có enum sau đây.Làm thế nào để tạo biểu thức động với một toán tử bitwise và enums?

[Flags] public enum Color { Red = 1, Blue = 2, Green = 4 } 

Bây giờ, tôi muốn sử dụng truy vấn sau để tìm áo sơ mi màu đỏ.

Shirts.Where(x => (x.Color & Color.Red) != 0) 

Và nó hoạt động tốt, nhưng khi tôi cố gắng để xây dựng này động:

var color= Expression.Constant(Color.Red); 
var property = Expression.Property(Expression.Parameter(typeof(Shirt)), "Color"); 
Expression.NotEqual(Expression.And(property, color), Expression.Constant(0)); 

tôi nhận được ngoại lệ sau đây:

Nhà điều hành nhị phân Và không được định nghĩa cho các loại 'MyEnums.Color' và 'MyEnums.Color'.

Tôi đang sử dụng .NET 4.5

Bất kỳ suy nghĩ?

Trả lời

8

Hãy thử chuyển đổi màu sắc và tài sản cho các loại cơ bản sử dụng Expression.Convert đầu tiên:

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)); 
+0

+1 để xây dựng biểu hiện phức tạp. Bạn luôn có thể xem cấu trúc của biểu thức bằng cách sử dụng LINQPad 'Dump' cho' Expression > exp = shirt => shirt.Color & Color.Red; ' –

+0

Wow, nhanh quá, và nó cũng hoạt động:) –

+0

@ IvanMilutinović Rất vui khi nó hoạt động - nó đã được một vài năm kể từ khi tôi cần phương pháp đó và tôi đã viết nó từ bộ nhớ chỉ ...: o :) –

Các vấn đề liên quan