通过MemberExpression获取属性类型

编程入门 行业动态 更新时间:2024-10-26 10:37:00
本文介绍了通过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获取属性类型

本文发布于:2023-11-12 11:38:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581398.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   类型   MemberExpression

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!