C # enum display on Expression.ToString ()

When I call the ToString () methods in an expression, the enum value is printed as integers. Is there any kind of format overload?

Perhaps I can create derviedclass from the expression and override some ToString method. Any thoughts?

Here is an example:

public enum LengthUnits { METRES, FEET }; Expression<Func<LengthUnits, bool>> isFeet = l => l == LengthUnits.FEET; string isFeetFunctinoAsString = isFeet.ToString(); 

Value isFeetFunctinoAsString:

  u => (Convert(u) = 1) 

I do not want 1, but KNIFE.

+4
source share
4 answers

This is not possible in an expression, because even before you can interfere with this expression, the enumeration has already been converted to an integer.

You can check if there is a binary expression with a parameter on the left or on the right, and convert it manually, but I will not recommend this.

+1
source
 Enum.GetName(Type MyEnumType, object enumvariable) 

From this question: C # line enumerations

Hope this is what you are looking for.

0
source
 myEnumValue.ToString ( "G" ); 

Taken from here

[Change]

 string isFeetFunctinoAsString = isFeet.ToString("G"); 
0
source

Here is what you need to do to extract the integer value and parse it as an enumeration type:

 BinaryExpression binaryExpression = (BinaryExpression)isFeet.Body; LengthUnits units = (LengthUnits)Enum.Parse (typeof(LengthUnits), binaryExpression.Right.ToString()); 

But that will not give you exactly what you want. C # enumerations resemble constants in such a way that their values ​​are literally transplanted to the source whenever they are referenced. The expression you have demonstrates this, because the literal value of the enum is embedded in the string representation of the expression.

0
source

All Articles