获取 lambda 表达式的表达式文本
我为 HtmlHelper 类编写了一个简单的扩展方法,例如
public static string GetExpressionNames<TModel>(this HtmlHelper<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;
}
“当前”,它只是接受模型属性(返回对象)上定义的 LambdaExpressions 数组,并将它们的表达式文本添加到一个字符串中,然后由该函数返回该字符串。问题是,对于字符串类型属性,它工作正常,但对于 int 属性,它返回空字符串作为表达式文本。原因是,对于返回 int 值的表达式,表达式主体如下图所示:
但对于字符串,就像
我认为转换方法是返回整数值的表达式导致空字符串返回为表达文字。我该如何解决这个问题?我只需要原始表达式文本,即 Convert(x.id)
的 Id 和 x.Name
的名称;后端如何处理并不重要。
I have written a simple extension method for HtmlHelper class like
public static string GetExpressionNames<TModel>(this HtmlHelper<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:
but for strings, its like
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我有这个扩展方法可以为我做这件事
您可能需要考虑进行额外的检查,因为如果 Convert 不包含成员表达式,您将收到强制转换错误。
I have this extension method to do it for me
You may want to consider putting extra checks as if Convert doesn't containt a memberexpression you will get a cast error.
你的问题不够完整,我无法知道你是否需要处理更复杂的场景(方法调用、添加等),但如果你只是期望表达式包含一个属性,并且你只想要属性的名称,您可以编写查看 lambda 表达式本身的
Body
的代码。如果主体是 Convert 表达式,您可以查看内部表达式。然后从其中的MemberAccess
表达式中提取属性名称。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 theMemberAccess
expression inside that.