开发者

Getting Expression Text for lambda Expressions

I have written a simple extension method for HtmlHelper class like

public static string GetExpressionNames<TModel>(this HtmlHelper&l开发者_Go百科t;TModel> helper,params Expression<Func<TModel,object>>[] args) where TModel:class
        {
            string returnStr = string.Empty;
            int i = 0;
            foreach (var x in args) 
            {
                returnStr += (++i).ToString() + ExpressionHelper.GetExpressionText(x) + "<br/>";
            }
            return returnStr;
        }

Currently, it's just accepting array of LambdaExpressions defined on Model properties (returning object) and add their expression text to a string which is then returned by this function. The problem is that, for string type properties it's working fine, but for int properties it's returning the empty string as expression text. The reason is that for expression that returns int values the body of expression looks like following image:

Getting Expression Text for lambda Expressions

but for strings, its like

Getting Expression Text for lambda Expressions

I think convert method is expressions that return integar values is causing the empty string to be returned as Expression text. How can I get around this problem? I just need original expression text i.e Id for Convert(x.id) and Name for x.Name; it does not matter how it is processing it at the back end.


I have this extension method to do it for me

public static string GetMemberName(this LambdaExpression expr) {
  var lexpr = expr;
  MemberExpression mexpr = null;
  if (lexpr.Body is MemberExpression) {
    mexpr = (MemberExpression) lexpr.Body;
  } else if (lexpr.Body is UnaryExpression) {
    mexpr = (MemberExpression) ((UnaryExpression) lexpr.Body).Operand;
  }
  if (mexpr == null) {
    return null;
  }
  return mexpr.Member.Name;
}

You may want to consider putting extra checks as if Convert doesn't containt a memberexpression you will get a cast error.


Your question isn't complete enough for me to know whether you need to handle more complex scenarios (method calling, addition, etc), but if you're just expecting the expression to contain a property, and you just want the property's name, you could write code that looks into the Body of the lambda expression itself. If the body is a Convert expression, you could look at the inner expression. Then pull the property's name off of the MemberAccess expression inside that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜