通过MemberExpression获取属性类型 [英] Get property type by MemberExpression

查看:134
本文介绍了通过MemberExpression获取属性类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请问类似的问题 here
,假设这个类型:

I ask similar question here , assume this type:

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

in HelperClass I just need property name(in this example IsAllowed) and property type (in this example Boolean) So I can get property name but I can't get property type. I see the property type in debugging as following picture shown:

那么你建议如何获取属性类型?

So what is your suggestion to get property type?

推荐答案

尝试将 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;
    }
}

这篇关于通过MemberExpression获取属性类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆