如何从 lambda 访问 属性

How to access property from lambda

我想重构这段代码以摆脱对 TModel, TValue

的依赖
public static string DescriptionFor<TModel, TValue>(this IHtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
    // null checks

    DescriptionAttribute descriptionAttribute = null;
    if (expression.Body is MemberExpression memberExpression)
    {
        descriptionAttribute = memberExpression.Member
            .GetCustomAttributes(typeof(DescriptionAttribute), false)
            .Cast<DescriptionAttribute>()
            .SingleOrDefault();
    }

    return descriptionAttribute?.Description ?? string.Empty;
}

有这样的调用:

@Html.DescriptionFor(x => x.MyModel.MyOtherModel.Property)

类似的事情

public static string DescriptionFor2<T>(Expression<Func<T>> expression)
{
    if (expression == null)
        throw new ArgumentNullException(nameof(expression));

    if (!(expression.Body is MemberExpression memberExpression))
    {
        return string.Empty;
    }

    foreach (var property in typeof(T).GetProperties())
    {
        if (property == ((expression.Body as MemberExpression).Member as PropertyInfo))
        {
            var attr = property
                        .GetCustomAttributes(typeof(DescriptionAttribute), false)
                        .Cast<DescriptionAttribute>()
                        .FirstOrDefault();

            return attr?.Description ?? string.Empty;
        }
    }

    return string.Empty;       
}

像那样调用:

@MyHtml.DescriptionFor2<MyOtherModel>(x => x.MyProperty);

但是这里有错误:

Delegate 'Func' does not take 1 arguments

你可以这样做:

void Main()
{
    Console.WriteLine(MyHtml.DescriptionFor2<Test>((t) => t.StringMember));
    Console.WriteLine(MyHtml.DescriptionFor2<Test>((t) => t.BooleanMember));
    Console.WriteLine(MyHtml.DescriptionFor2<Test>((t) => t.IntegerMember));
}

public class Test
{
    [Description("This is a string member")]
    public string StringMember { get; set; }
    [Description("This is a boolean member")]
    public bool BooleanMember { get; set; }
    [Description("This is a integer member")]
    public int IntegerMember { get; set; }
}

public static class MyHtml
{
    public static string DescriptionFor2<T>(Expression<Func<T, dynamic>> expression)
    {
        var result = string.Empty;
        var member = GetMemberExpression(expression)?.Member?.Name;
        if (member != null)
        {
            var property = typeof(T).GetProperty(member);
            if (property != null)
            {
                var attr = property
                            .GetCustomAttributes(typeof(DescriptionAttribute), false)
                            .Cast<DescriptionAttribute>()
                            .FirstOrDefault();

                result = attr?.Description ?? string.Empty;
            }
        }

        return result;
    }

    private static MemberExpression GetMemberExpression<T>(Expression<Func<T, dynamic>> expression)
    {
        var member = expression.Body as MemberExpression;
        var unary = expression.Body as UnaryExpression;
        return member ?? (unary != null ? unary.Operand as MemberExpression : null);
    }
}

public class DescriptionAttribute : Attribute
{
    public string Description { get; set; }

    public DescriptionAttribute(string description)
    {
        Description = description;
    }
}

它涉及获取表达式的主体作为成员并使用其名称解析对象上的 属性。 dynamic 数据类型用于去除第二个类型参数,但是您也可以显式定义它以更好地捕获编译时错误:

public static string DescriptionFor2<T, U>(Expression<Func<T, U>> expression)

并调用它:

MyHtml.DescriptionFor2<Test, string>((t) => t.StringMember);
MyHtml.DescriptionFor2<Test, bool>((t) => t.BooleanMember);
MyHtml.DescriptionFor2<Test, int>((t) => t.IntegerMember);

编辑:已编辑答案,因为初始解决方案不适用于值类型,请参见Expression for Type members results in different Expressions (MemberExpression, UnaryExpression)