【问题标题】:Get property names from lambda function [duplicate]从 lambda 函数获取属性名称
【发布时间】:2014-08-23 12:42:44
【问题描述】:

ASP.NET MVC 以某种方式从以下结构中获取属性名称:

@Html.LabelFor(model => model.UserName)

我也想实现这个魔法来减少我项目中的魔法字符串数量。你能帮我吗?简单例子:

// that's how it works in my project
this.AddModelStateError("Password", "Password must not be empty"); 

// desired result
this.AddModelStateError(x => x.Password, "Password must not be empty"); 

【问题讨论】:

  • 你看过mvc框架是怎么做的吗?源是免费的。
  • 不知道。谢谢。我会设法找到它。
  • 在 ModelMetaData.FromLambdaExpression 中找到解决方案 :) 非常感谢。

标签: c# lambda


【解决方案1】:

Asp MVC 的 LabelFor 助手采用 Expression<Func<TModel, Value>>。此表达式可用于检索Func<TModel,Value> 指向的属性信息,进而可以通过PropertyInfo.Name 检索其名称。

然后,Asp MVC 将 HTML 标记上的 name 属性分配为与此名称相同。因此,如果您选择一个名为IdLabelFor 属性,您最终会得到<label name='Id'/>

为了从Expression<Func<TModel,Value>> 中获取PropertyInfo,您可以查看this answer,它使用以下代码:

public PropertyInfo GetPropertyInfo<TSource, TProperty>(
    TSource source,
    Expression<Func<TSource, TProperty>> propertyLambda)
{
    Type type = typeof(TSource);

    MemberExpression member = propertyLambda.Body as MemberExpression;
    if (member == null)
        throw new ArgumentException(string.Format(
            "Expression '{0}' refers to a method, not a property.",
            propertyLambda.ToString()));

    PropertyInfo propInfo = member.Member as PropertyInfo;
    if (propInfo == null)
        throw new ArgumentException(string.Format(
            "Expression '{0}' refers to a field, not a property.",
            propertyLambda.ToString()));

    if (type != propInfo.ReflectedType &&
        !type.IsSubclassOf(propInfo.ReflectedType))
        throw new ArgumentException(string.Format(
            "Expresion '{0}' refers to a property that is not from type {1}.",
            propertyLambda.ToString(),
            type));

    return propInfo;
}

【讨论】:

    猜你喜欢
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多