Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>What about this?</p> <pre><code>public class KeyGeneratorVisitor : ExpressionVisitor { protected override Expression VisitParameter(ParameterExpression node) { return Expression.Parameter(node.Type, node.Type.Name); } protected override Expression VisitMember(MemberExpression node) { if (CanBeEvaluated(node)) { return Expression.Constant(Evaluate(node)); } else { return base.VisitMember(node); } } private static bool CanBeEvaluated(MemberExpression exp) { while (exp.Expression.NodeType == ExpressionType.MemberAccess) { exp = (MemberExpression) exp.Expression; } return (exp.Expression.NodeType == ExpressionType.Constant); } private static object Evaluate(Expression exp) { if (exp.NodeType == ExpressionType.Constant) { return ((ConstantExpression) exp).Value; } else { MemberExpression mexp = (MemberExpression) exp; object value = Evaluate(mexp.Expression); FieldInfo field = mexp.Member as FieldInfo; if (field != null) { return field.GetValue(value); } else { PropertyInfo property = (PropertyInfo) mexp.Member; return property.GetValue(value, null); } } } } </code></pre> <p>This will replace the complex constant expressions to their original values as well as the parameter names to their type names. So just have to create a new <code>KeyGeneratorVisitor</code> instance and call its <code>Visit</code> or <code>VisitAndConvert</code> method with your expression.</p> <p>Please note that the <code>Expression.ToString</code> method will be also invoked on your complex types, so either override their <code>ToString</code> methods or write a custom logic for them in the <code>Evaluate</code> method.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload