通过MemberExpression获取属性类型

时间:2012-04-19 08:15:25

标签: c# c#-4.0 properties expression

我问类似问题here ,假设这种类型:

 public class Product {

public string Name { get; set; }
public string Title { get; set; }
public string Category { get; set; }
public bool IsAllowed { get; set; }

}

这个使用MemberExpression的人:

public class HelperClass<T> {

    public static void Property<TProp>(Expression<Func<T, TProp>> expression) {

        var body = expression.Body as MemberExpression;

        if(body == null) throw new ArgumentException("'expression' should be a member expression");

        string propName = body.Member.Name;
        Type proptype = null;

    }

}

我这样用:

HelperClass<Product>.Property(p => p.IsAllowed);

HelperClass中我只需要属性名称(在此示例中为IsAllowed)和属性类型(在此示例中为Boolean)所以我可以获取属性名称但我无法获取属性类型。我在调试中看到了属性类型,如下图所示:

enter image description here

那么您建议获得房产类型是什么?

1 个答案:

答案 0 :(得分:26)

尝试将body.Member投射到PropertyInfo

public class HelperClass<T>
{
    public static void Property<TProp>(Expression<Func<T, TProp>> expression)
    {
        var body = expression.Body as MemberExpression;

        if (body == null)
        {
            throw new ArgumentException("'expression' should be a member expression");
        }

        var propertyInfo = (PropertyInfo)body.Member;

        var propertyType = propertyInfo.PropertyType;
        var propertyName = propertyInfo.Name;
    }
}