简体   繁体   English

表达式树库和枚举之间的关系

[英]Expression tree library and relations between enums

In C# I can successfully compare enum values using any relational operators, like below: 在C#中,我可以使用任何关系运算符成功比较枚举值,如下所示:

var res  = SomeEnumType.First < SomeEnumType.Second

While trying to accomplish the same using expression library: 在尝试使用表达式库完成相同的操作时:

var arg1 = Expression.Constant(SomeEnumType.First);
var arg2 = Expression.Constant(SomeEnumType.Second);
var res  = Expression.LessThan(arg1, arg2);

the following error is thrown (analogically for <=, > and >=): 抛出以下错误(类似于<=,>和> =):

The binary operator LessThan is not defined for the types 'Prog.SomeEnumType' and 'Prog.SomeEnumType'. 没有为类型'Prog.SomeEnumType'和'Prog.SomeEnumType'定义二进制运算符LessThan。

What is the correct way to fix it? 修复它的正确方法是什么?

You have to convert enum value to the enum underlying type: 您必须将枚举值转换为枚举基础类型:

var arg1 = Expression.Constant(SomeEnumType.First);
var arg2 = Expression.Constant(SomeEnumType.Second);
var enumType = Enum.GetUnderlyingType(typeof (SomeEnumType));
var res = Expression.LessThan(Expression.Convert(arg1, enumType), Expression.Convert(arg2, enumType));

实际上你可以将它转换为int(或你的枚举所基于的任何类型)来实现所需的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM