通过MemberExpression获取属性类型 [英] Get property type by MemberExpression
本文介绍了通过MemberExpression获取属性类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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;
}
}
我用它像这样的:
I use it like this:
HelperClass<Product>.Property(p => p.IsAllowed);
在助手类
我只需要属性名称(在这个例子中 IsAllowed
)和属性类型(在这个例子布尔
),这样我就可以得到属性名称,但我可以'吨得到属性类型。我看到在调试物业类型,如下图所示:
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屋!
查看全文