Expression.ToString() 上的 C# 枚举显示
当我对表达式调用 ToString() 方法时,枚举值将打印为整数。是否存在某种格式过载?
也许我可以从表达式创建一个派生类并覆盖一些 ToString 方法。有什么想法吗?
这是一个示例:
public enum LengthUnits { METRES, FEET };
Expression<Func<LengthUnits, bool>> isFeet = l => l == LengthUnits.FEET;
string isFeetFunctinoAsString = isFeet.ToString();
isFeetFunctinoAsString 的值是:
u => (Convert(u) = 1)
我不需要 1,而是 FEET。
When I call the ToString() methods on an expression, the enum value are printed as integers. Is there some format overload ?
Maybe I can create an derviedclass from expression and override some ToString Method. Any thoughts ?
Here is a sample :
public enum LengthUnits { METRES, FEET };
Expression<Func<LengthUnits, bool>> isFeet = l => l == LengthUnits.FEET;
string isFeetFunctinoAsString = isFeet.ToString();
The value of isFeetFunctinoAsString is :
u => (Convert(u) = 1)
I do not want the 1 but FEET .
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这在表达式中是不可能的,因为甚至在您可以干扰表达式之前,枚举已经转换为整数。
您可能想检查何时存在带有左侧或右侧参数的二进制表达式,并手动转换,但我不建议这样做。
This is not possible in an expression, as even before you can interfere with the expression, the enum has already been converted to an integer.
You might want to check when there is a binaryexpression with the parameter on the left or right side, and convert by hand, but I won't recommend that.
来自这个问题: C# String enums
希望这就是您正在寻找的内容。
From this question: C# String enums
Hope this is what you are looking for.
取自此处
[编辑]
Taken from here
[Edit]
以下是您需要执行的操作来提取整数值并将其解析为枚举类型:
但这并不能准确地提供您想要的内容。 C# 枚举就像常量,每当引用它们时,它们的值都会被逐字移植到源中。您所拥有的表达式演示了这一点,因为枚举的文字值嵌入在表达式的字符串表示形式中。
Here is what you would need to do to extract the integer value and parse it as the enumeration type:
But that won't give you exactly what you want. C# enumerations are like constants in the way that their values are literally transplanted into the source whenever they are referenced. The expression you have is demonstrating this as the literal value of the enumeration is embedded in the expression's string representation.