如何从Lambda访问属性

时间:2019-03-27 14:15:42

标签: c# delegates system.reflection

我想重构此代码以摆脱对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);

但是这里有错误:

  

代表'Func'不接受1个参数

1 个答案:

答案 0 :(得分:0)

您可以这样做:

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)