本文介绍了通过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获取属性类型
发布评论