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

前端之家收集整理的这篇文章主要介绍了c# – 通过MemberExpression获取属性类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我问类似的问题 here
,假设这种类型:
  1. public class Product {
  2.  
  3. public string Name { get; set; }
  4. public string Title { get; set; }
  5. public string Category { get; set; }
  6. public bool IsAllowed { get; set; }
  7.  
  8. }

而这个使用MemberExpression的

  1. public class HelperClass<T> {
  2.  
  3. public static void Property<TProp>(Expression<Func<T,TProp>> expression) {
  4.  
  5. var body = expression.Body as MemberExpression;
  6.  
  7. if(body == null) throw new ArgumentException("'expression' should be a member expression");
  8.  
  9. string propName = body.Member.Name;
  10. Type proptype = null;
  11.  
  12. }
  13.  
  14. }

我这样用:

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

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

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

解决方法

尝试将body.Member转换为PropertyInfo
  1. public class HelperClass<T>
  2. {
  3. public static void Property<TProp>(Expression<Func<T,TProp>> expression)
  4. {
  5. var body = expression.Body as MemberExpression;
  6.  
  7. if (body == null)
  8. {
  9. throw new ArgumentException("'expression' should be a member expression");
  10. }
  11.  
  12. var propertyInfo = (PropertyInfo)body.Member;
  13.  
  14. var propertyType = propertyInfo.PropertyType;
  15. var propertyName = propertyInfo.Name;
  16. }
  17. }

猜你在找的C#相关文章