18

我在这里问类似的问题 ,假设这种类型:

 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)所以我可以获取属性名称但我无法获取属性类型。我在调试中看到属性类型如下图所示:

在此处输入图像描述

那么您对获取属性类型有什么建议?

4

1 回答 1

33

尝试投射body.MemberPropertyInfo

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;
    }
}
于 2012-04-19T08:20:35.680 回答