加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 通过MemberExpression获取属性类型

发布时间:2020-12-15 18:10:36 所属栏目:百科 来源:网络整理
导读:我问类似的问题 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 H
我问类似的问题 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)所以我可以获取属性名称,但是我无法获取属性类型.我在调试中看到属性类型如下图所示:

那么你建议如何获得房产类型?

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读